从数组生成php中的switch case?

时间:2012-12-17 22:45:56

标签: php foreach switch-statement

是否可以使用数组为php中的开关生成案例?类似的东西:

$x=array(
    0 => 'foo',
    1 => 'bar',
    2 => 'foobar'
);

$y='foobar'

switch($y) {
    foreach($x as $i) {
        case $i:
            print 'Variable $y tripped switch: '.$i.'<br>';
            break;
    }
}

我希望能够从数据库中提取案例值并使用while()循环遍历它们。

2 个答案:

答案 0 :(得分:6)

我相信你所寻找的东西就是这个

foreach ($x as $i) {
    switch($i){
        case $y:
            print 'Variable $x tripped switch: '.$i.'<br>';
            break;
    }
}

答案 1 :(得分:4)

没有。交换机是一个交换机,但您可以使用数组键来选择正确的值。基本上在您的数组中,您将使键和值相同,然后您可以使用if函数,如下所示:

if ($array[$key]) ....