note 113633 added to function.strstr
| From: | laszlo dot heredy at gmail dot com | Date: | Thu, 07 Nov 2013 21:39:23 +0000 |
| Subject: | note 113633 added to function.strstr | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-197459@lists.php.net to get a copy of this message | ||
strstr() is not a way to avoid type-checking with strpos().
If $needle is the last character in $haystack, and testing $needle as a boolean by itself would
evaluate to false, then testing strstr() as a boolean will evaluate to false (because, if
successful, strstr() returns the first occurrence of $needle along with the rest of $haystack).
<?php
findZero('01234'); // found a zero
findZero('43210'); // did not find a zero
findZero('0'); // did not find a zero
findZero('00'); // found a zero
findZero('000'); // found a zero
findZero('10'); // did not find a zero
findZero('100'); // found a zero
function findZero($numberString) {
if (strstr($numberString, '0')) {
echo 'found a zero';
} else {
echo 'did not find a zero';
}
}
?>
Also, strstr() is far more memory-intensive than strpos(), especially with longer strings as your
$haystack, so if you are not interested in the substring that strstr() returns, you shouldn't
be using it anyway.
There is no PHP function just to check only _if_ $needle occurs in $haystack; strpos() tells you if
it _doesn't_ by returning false, but, if it does occur, it tells you _where_ it occurs as an
integer, which is 0 (zero) if $needle is the first part of $haystack, which is why testing if
(strpos($needle, $haystack)===false) is the only way to know for sure if $needle is not part of
$haystack.
My advice is to start loving type checking immediately, and to familiarize yourself with the return
value of the functions you are using.
Cheers.
----
Server IP: 192.41.45.150
Probable Submitter: 64.1.208.234
----
Manual Page -- http://php.net/manual/en/function.strstr.php
Edit -- https://master.php.net/note/edit/113633
Del: integrated -- https://master.php.net/note/delete/113633/integrated
Del: useless -- https://master.php.net/note/delete/113633/useless
Del: bad code -- https://master.php.net/note/delete/113633/bad+code
Del: spam -- https://master.php.net/note/delete/113633/spam
Del: non-english -- https://master.php.net/note/delete/113633/non-english
Del: in docs -- https://master.php.net/note/delete/113633/in+docs
Del: other reasons-- https://master.php.net/note/delete/113633
Reject -- https://master.php.net/note/reject/113633
Search -- https://master.php.net/manage/user-notes.php