note 80010 added to function.strpos
| From: | Lau at osu1 dot php dot net | Date: | Mon, 24 Dec 2007 12:45:37 +0000 |
| Subject: | note 80010 added to function.strpos | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-133970@lists.php.net to get a copy of this message | ||
WARNING: The documentation says:
"Use the === operator for testing the return value of this function"
but it should say:
"Use '!== false' or '=== false' for testing the return value of this
function"
Therefore to test if a needle occurst in a hastack do this:
if ( strpos($haystack, $needle) !== false){
echo 'found needle in haystack!';
}
Using '=== true' or '!== true' or '== true' or '== false'
will all return the wrong value when the needle is found in the haystack.
using ' >= 0 ' returns the wrong value when the needle is not found in the haystack.
By "wrong value" I mean a value that is counter-intuitive but is never-the-less correct
according to the weird way in which strpos has been coded. Why on earth didn't they just return
-1 if the needle was not found? Then we could just test for >= 0
Here's a full list of the value returned:
(strpos("bbb", "aaa") >= 0) returns true EXPECTED FALSE
(strpos("bbb", "aaa") == true) returns false expected false
(strpos("bbb", "aaa") == false) returns true expected true
(strpos("bbb", "aaa") === true) returns false expected false
(strpos("bbb", "aaa") === false) returns true expected true
(strpos("bbb", "aaa") !== false) returns false expected false
(strpos("bbb", "aaa") !== true) returns true expected true
(strpos("aaa", "aaa") >= 0) returns true expected true
(strpos("aaa", "aaa") == true) returns false EXPECTED TRUE
(strpos("aaa", "aaa") == false) returns true EXPECTED FALSE
(strpos("aaa", "aaa") === true) returns false EXPECTED TRUE
(strpos("aaa", "aaa") !== false) returns true expected true
(strpos("aaa", "aaa") === false) returns false expected false
(strpos("aaa", "aaa") !== true) returns true EXPECTED FALSE
----
Server IP: 69.147.83.197
Probable Submitter: 211.29.160.24
----
Manual Page -- http://www.php.net/manual/en/function.strpos.php
Edit -- https://master.php.net/note/edit/80010
Del: integrated -- https://master.php.net/note/delete/80010/integrated
Del: useless -- https://master.php.net/note/delete/80010/useless
Del: bad code -- https://master.php.net/note/delete/80010/bad+code
Del: spam -- https://master.php.net/note/delete/80010/spam
Del: non-english -- https://master.php.net/note/delete/80010/non-english
Del: in docs -- https://master.php.net/note/delete/80010/in+docs
Del: other reasons-- https://master.php.net/note/delete/80010
Reject -- https://master.php.net/note/reject/80010
Search -- https://master.php.net/manage/user-notes.php