问题
How can I use an array in the case of a switch? This doesn't work and always take the default (3):
switch ($my_array) {
case array('george','paul'):
$id = 1;
break;
case array('paul','max'):
$id = 2;
break;
case array('eric'):
$id = 3;
break;
//default
default:
$id = 3;
break;
}
回答1:
Your example should work, according to the PHP manual on array operators:
$a == $b: TRUE if $a and $b have the same key/value pairs.
Since switch/case uses weak comparison, arrays are compared by using the == operator.
I've put a working example onto codepad: http://codepad.org/MhkGpPRp
回答2:
PHP can switch on arrays, though you do need to have exactly the same keys of all the elements for the comparison to succeed. You might need to use array_values() to normalize the keys of $my_array. Otherwise it should work. $my_array = array('paul','max'); should give $id=2.
回答3:
You can try to use some like this:
switch (serialize($junctions)) {
case serialize(array('george','paul')):
$id = 1;
break;
case serialize(array('paul','max')):
$id = 2;
break;
case serialize(array('eric')):
$id = 3;
break;
//default
default:
$id = 3;
break;
}
But you really want it?
回答4:
switch() statements are intended to match single conditions. I don't think there will be a way to use a switch for this. You need to use an if else chain instead:
if (in_array('george', $array) && in_array('paul', $array) && !in_array('max', $array)) {
$id = 1;
}
else if(in_array('paul', $array) && in_array('max', $array)) {
$id = 2;
}
else if (in_array('eric', $array)) {
$id = 3;
}
else {
$id = 3;
}
According to array operator rules, you can use ==, but the array members must be in the same order. Technically, it is only the keys and values that must match, but for a numeric-indexed array, this equates to the members being in the same numeric order.
if ($array == array('john', 'paul')) {
$id = 1;
}
else if ($array == array('paul', 'max')) {
$id = 2;
}
else if ($array == array('eric')) {
$id = 3;
}
else {
$id = 3;
}
来源:https://stackoverflow.com/questions/8105244/how-to-use-an-array-in-case