How to use an array in case?

2019-09-08 22:45发布

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;

    }

4条回答
叼着烟拽天下
2楼-- · 2019-09-08 23:23

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

查看更多
啃猪蹄的小仙女
3楼-- · 2019-09-08 23:29

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;
}
查看更多
【Aperson】
4楼-- · 2019-09-08 23:35

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?

查看更多
ゆ 、 Hurt°
5楼-- · 2019-09-08 23:44

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.

查看更多
登录 后发表回答