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;
}
Your example should work, according to the PHP manual on array operators:
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
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 anif else
chain instead: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.You can try to use some like this:
But you really want it?
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.