for my purposes I did this:
<?php
$mystring = 'Gazole,';
$findme = 'Sans Plomb 95';
$pos = strpos($mystring, $findme);
if ($pos >= 0) {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
} else {
echo "The string '$findme' was not found in the string '$mystring'";
}
?>
However, it always executes this branch:
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
although the string I 'm searching for doesn't exist.
Please help, thx in advance :))
The correct way to do it is:
if ($pos !== false) {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
} else {
echo "The string '$findme' was not found in the string '$mystring'";
}
See the giant red warning in the documentation.
strpos
returns a boolean false
in case the string was not found. Your test should be $pos !== false
rather than $pos >= 0
.
Note that the standard comparison operators do not consider the type of the operands, so that false
is coerced to 0
. The ===
and !==
operators yield true
only if the types and the values of the operands match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With