Using strstr inside a switch php
Asked Answered
T

3

7

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?

Tout answered 14/7, 2011 at 10:5 Comment(1)
Actually foreach solution by php-coder is better to use switch. it will reduce line of codes.Modernistic
R
11
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.

Radon answered 14/7, 2011 at 10:8 Comment(0)
A
11

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";
    }
}
Asthenia answered 14/7, 2011 at 10:10 Comment(2)
Definitely +1. Definitely. I'd give you +2 if I could.Colene
better answer to this case +1, but @Radon snippet is interesting for realize a specific action.Venatic
E
2

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;
}
Eous answered 14/7, 2011 at 10:7 Comment(1)
@William Jones can you pls avoid such words in public, that to tech discussion.Modernistic

© 2022 - 2024 — McMap. All rights reserved.