Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate switch cases in php from an array?

Is it possible to generate the cases for a switch in php using an array? Something like:

$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;
    }
}

I would like to be able to pull the case values from a database and loop through them with a while() loop.

like image 873
mopsyd Avatar asked Dec 17 '12 22:12

mopsyd


2 Answers

I believe what you are looking for is something along the line of this

foreach ($x as $i) {
    switch($i){
        case $y:
            print 'Variable $x tripped switch: '.$i.'<br>';
            break;
    }
}
like image 136
Kevin Barnard Avatar answered Oct 17 '22 07:10

Kevin Barnard


No. A switch is a switch but you can use the array-key to pick the right value. Basically in your array you would make key and value is the same and then you can use if function like so:

if ($array[$key]) ....
like image 21
Micromega Avatar answered Oct 17 '22 08:10

Micromega