I have an array and I need to be able to switch case based on the array values. I've tried the following but something is wrong and it's not working:

$section = array(
 'varOne' 	=> 'This is variable One', 
 'Two' 	=> 'Work with variable Two', 
 'var_Three' => 'Post var three',
 'myDefault' => 'This is my default');

switch($section) {
case 'postProject': 
   echo section['varOne'];
   break;
case 'Two': 
   echo $section['Two'].$addSomething;
   break;
case 'var_Three': 
   echo $section['var_Three'].$more;
   break;
default 
   echo $section['myDefault'];
}

What am I missing? Basicly I'd like to match case by array's KEY adn output areray's VALUE... Honestly I'm not on a short hand with arrays.

    I'm not really sure what you're trying to do here, functionally. If $section is an array, then switch($section) does not make such since, as it does not refer to any specific value but to the array as a whole. In any case, if you already know the key value, there's really no reason for a switch. You could just do something like:

    $someValue = $_POST['some_field']; // perhaps value comes from a form?
    if(array_key_exists($someValue, $section))
    {
      echo $section[$someValue];
    }
    else
    {
      echo $section['myDefault'];
    }
    

      Yes, I understand where I was wrong. I need first to get the key value and then run it through the switch case.

      I've read that if/else logic is faster then switch case... Is it?

        As far as speed, I don't know which (if either) is faster; but you're probably only talking a few milliseconds difference at most, and for most applications you'd be better off choosing the implementation that's easier to read and maintain. (Code that takes 0.023 seconds to process correctly is much better than code that takes 0.018 seconds to process incorrectly. 🙂 )

          Write a Reply...