phptypesstrpos

strpos() returning incorrect result when the needle string is an integer-type value


I am simply trying to see if a numeric year is contained inside a string of car years and models. I would think the following code should show $my_str as FALSE. But it return 9. How? The 9 position is a lower case "l". Makes no sense to me unless the fact my needle is numeric screws things up. But later I will create a loop and really want $my_needle to be numeric.

$my_haystack = "2007 Cadillac CTS";
$my_needle = 1900;
$my_str = strpos($my_haystack, $my_needle);
echo "my_str=$my_str"; //Returns my_str=9

Solution

  • You can't search for an INT inside a string using this function, you could convert the int to string before searching, like this:

    $my_haystack = "2007 Cadillac CTS";
    $my_needle = 1900;
    $my_str = strpos($my_haystack, strval($my_needle));