5

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.

3
  • 2
    No. What do you want to use this for? Why do you think you need a switch/case? Commented Dec 17, 2012 at 22:47
  • 3
    Whatever you are trying to do, switch is overcomplicating it. What you want is not possible, and for good reason - that code could be written as simply foreach($x as $i) { if ($i == $y) { print 'Variable $y tripped switch: '.$i.'<br>'; } } (assuming you got your $xs and your $is confused in that code sample) Commented Dec 17, 2012 at 22:52
  • I didn't really need it, it was just something I wound up tinkering with out of speculation. Commented Dec 17, 2012 at 23:00

2 Answers 2

8

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

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]) ....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.