3

Assuming this works properly for telling if a substring is in a string, is there a more concise way to do this?

if(is_int(strpos($haystack, $needle))){
   ...
}
John R
  • 2,920
  • 13
  • 48
  • 62

2 Answers2

6

I wouldn't do it that way. Just make a strict comparison to FALSE.

$found = strpos($haystack, $needle) !== FALSE;
alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    @bfavaretto It's a needless extra function call, which among other things is [expensive](http://stackoverflow.com/questions/3691625/why-are-php-function-calls-so-expensive). – alex May 07 '12 at 02:03
  • This is correct, strpos returns FALSE when no needle is found. – kintsukuroi Apr 20 '19 at 06:44
3

Not really. It really comes down to your preference for which one is the clearest way to express what you're doing. Some alternatives:

if( strpos( $h, $n ) !== FALSE ){
    // stuff
}

if( strpos( $h, $n ) > -1 ){
    // stuff
}

The most common approach is probably to use the strict FALSE comparison, so if you're working on an open-source project or have a lot of other people using your code, consider that option.

derekerdmann
  • 17,696
  • 11
  • 76
  • 110