Search code examples
phpstrpos

Strange behaviour of strpos and Ø


This seems odd to me but maybe there's a simple explanation.

Why does the following block of code result in false despite the needle definitely being part of the haystack?

if(strpos("Ø25xØ2", "Ø")){
    echo "true";
} else {
    echo "false";
}

Solution

  • strpos is finding that string at offset 0, which evaluates as false. To truly detect if it's not found, you need to explicitly check both type and value using either === or !== operators, for example:

    if (strpos("Ø25xØ2", "Ø") !== false) {
        echo "true";
    } else {
        echo "false";
    }
    

    This is quite well covered in the manual too.