|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #1540 strpos(): returning FALSE or 0 is the same
Submitted: 1999-06-14 22:41 UTC Modified: 1999-06-15 09:24 UTC
From: a dot suatoni at itaca dot it Assigned: cmv (profile)
Status: Closed Package: Misbehaving function
PHP Version: 3.0.9 OS: Digital Unix 3.2D
Private report: No CVE-ID: None
 [1999-06-14 22:41 UTC] a dot suatoni at itaca dot it
When using strpos() there is no way to differentiate between a "not found" condition and a return of 0 index. 

According to bug #1234

  [1999-03-14 14:26:35] rasmus

  FALSE is defined as the empty string "" which strpos() will return when a match is not found.  If a match is found in the first position it will return 0.

According to bug #1323

  [1999-04-16 16:03:08] rasmus

  Untrue.  false is "" which is different from a string index of 0.  You just have to check it correctly.

However, the following code snippet demonstrates that there is no straight way to determine the real result of strpos().



echo "Test 1\n";
if (strpos("abcd", "e") == FALSE)
  echo "it should enter here\n";
  echo "it should NOT enter here\n";

echo "Test 2\n";
if (strpos("abcd", "a") == FALSE)
  echo "it should NOT enter here\n";
  echo "it should enter here\n";



The above code, when interpreted with "php -q < snippet", produces the following output:

# php -q < snippet
Test 1
it should enter here
Test 2
it should NOT enter here


I've noted that strstr(), since it always returns a string, does not suffer the same problem as above, and it can be used as a temporary workaround in case one just wants to check if the needle is contained in the haystack. The problem has been noted also in previous versions of PHP3.


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [1999-06-15 09:24 UTC] cmv at cvs dot php dot net
Actually, Rasmus said:

"No, the two things actually return different things.  0 is returned if the char is found at position 0 and '' (a null string) is returned if the char is not found at all.  Granted, both evaluate to FALSE in a conditional which is the source of the problem."

So, the function works as documented.

Basically, you're using the wrong function.  Try strstr():

if (strstr("abcde","a")) {
   echo "it's in there";
} else {
   echo "it's not";

PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Tue Aug 20 09:01:28 2019 UTC