Using strstr inside a switch php

William Jones picture William Jones · Jul 14, 2011 · Viewed 8.1k times · Source

I just cannot think of the code. I have waay too many if statments which I want to change to be a switch statement, but I cannot find of the logic.

At the moment I have:

if(strstr($var,'texttosearch'))
   echo 'string contains texttosearch';

if(strstr($var,'texttosearch1'))
   echo 'string contains texttosearch1';

if(strstr($var,'texttosearch2'))
   echo 'string contains texttosearc2h';

//etc etc...

But how can I achieve the same within a switch?

Answer

KingCrunch picture KingCrunch · Jul 14, 2011
switch (true) {
  case strstr($var,'texttosearch'):
    echo 'string contains texttosearch';
    break;
  case strstr($var,'texttosearch1'):
    echo 'string contains texttosearch1';
    break;
  case strstr($var,'texttosearch2'):
    echo 'string contains texttosearc2h';
    break;
}

Note, that this is slightly different to your own solution, because the switch-statement will not test against the other cases, if an earlier already matches, but because you use separate ifs, instead if if-else your way always tests against every case.