Search code examples
phptypesstrpos

Integer-type value not found with strpos(), although the number is in the haystack string


$row['solved']= "12|10|3";
$id=10;
$pos = strpos($row['solved'], $id);
if ($pos !== false){
    echo "String found!";       
    exit;
}
echo "String not found!";

Why does this always return "String not found"?


Solution

  • As per the PHP docs:

    If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

    Your $id argument is an integer, and accordingly used as an ordinal value of the character (generally the ASCII value.) In this scenario, the ASCII value 10 is representative of the \n linefeed character, so you are searching $row['solved'] for this, which in this particular $row['solved'] value will be not found.

    To fix this, use:

    $pos = strpos($row['solved'], (string)$id);