Is it OK to replace multiple comparisons by using strpos()?
Example:
changing
if ( $linecounter == $extra1 || $linecounter == $extra2 || $linecounter == 5 )
{
...
}
to
$ok = ' ' . $extra1 . $extra2 . '5';
if ( strpos($ok, $linecounter) > 0 )
{
...
}
No, it's not OK because that's not what strpos
is for. It's easy to find problematic examples in the general case (e.g. $linecounter == 15
and $extra2 == 1
-- the strpos
check will succeed when it should not have).
If you want to lose the separate conditions so much, workable alternatives would be either a switch
statement or in_array
:
switch($linecounter) {
case $extra1: case $extra2: case 5:
// whatever
break;
}
if (in_array($linecounter, [$extra1, $extra2, 5])) {
// whatever
}
As an aside, using strpos
with a greater-than-zero test like that is not good style. What you want to say is "if it's found in the string", so write exactly that and lose the "prefix a space" hack:
if ( strpos($extra1 . $extra2 . '5', $linecounter) !== false )