从数组生成php中的switch case?

mop*_*syd 5 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 7

我相信你所寻找的东西都是这样的

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


Gig*_*egs 4

不。开关就是开关,但您可以使用数组键来选择正确的值。基本上在你的数组中,你会让键和值相同,然后你可以使用 if 函数,如下所示:

如果 ($array[$key]) ....