Using strstr inside a switch php

谁都会走 提交于 2019-12-05 10:43:06
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.

I think you can't achieve this with switch (more elegant than now) because it compare values but you want compare only part of values. Instead you may use loop:

$patterns = array('texttosearch', 'texttosearch1', 'texttosearch2');
foreach ($patterns as $pattern) {
    if (strstr($var, $pattern)) {
        echo "String contains '$pattern'\n";
    }
}
Mads Ohm Larsen

You can do it the other way around:

switch(true) {
case strstr($var, "texttosearch"):
    // do stuff
    break;
case strstr($var, "texttosearch1"):
    // do other stuff
    break;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!