Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php 5 strpos() difference between returning 0 and false?

Tags:

if(strpos("http://www.example.com","http://www.")==0){ // do work} 

I'd expect this to resolve as true, which it does. But what happens when I do

if(strpos("abcdefghijklmnop","http://www.")==0){// do work} 

This also passes on php 5 because as far as I can work out the strpos returns false which translates as 0.

Is this correct thinking/behaviour? If so what is the workaround for testing for that a substring is at the beginning of another string?

like image 614
blippy Avatar asked Mar 07 '10 15:03

blippy


People also ask

What does Strpos return in PHP?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.

What does Strpos return in PHP if not found?

Return Value: Returns the position of the first occurrence of a string inside another string, or FALSE if the string is not found.


1 Answers

Yes, this is correct / expected behavior :

  • strpos can return 0 when there is a match at the beginning of the string
  • and it will return false when there is no match

The thing is you should not use == to compare 0 and false ; you should use ===, like this :

if(strpos("abcdefghijklmnop","http://www.") === 0) {  } 

Or :

if(strpos("abcdefghijklmnop","http://www.") === false) {  } 


For more informations, see Comparison Operators :

  • $a == $b will be TRUE if $a is equal to $b.
  • $a === $b will be TRUE if $a is equal to $b, and they are of the same type.

And, quoting the manual page of strpos :

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "".
Please read the section on Booleans for more information.
Use the === operator for testing the return value of this function.

like image 131
Pascal MARTIN Avatar answered Sep 24 '22 17:09

Pascal MARTIN