Search code examples
phpstrpos

strpos() doesn't return a truthy result when matching the start of the string


I'm trying to use strpos() to find a string inside another string, but for some reason it isn't working for a certain string, even though it's working for the other one. What am I doing wrong?

if (strpos("show me how to dance", "show me")) {
    echo "true1";
}
if (strpos("my name is name", "name")) {
    echo "true2";
}

Result:

true2

Expected Result:

true1true2

Solution

  • strpos returns the index of the occurrence in the string (or false if it isn't found). When this index is 0, the condition: (strpos("show me how to dance", "show me")) is evaluated as false (because in PHP: 0 == false is true). To be sure the needle is found (even at index 0) you need to use a strict comparison:

    if (strpos("show me how to dance", "show me") !== false)
    

    Since php 8.0, you can use str_contains that always returns a boolean:

    if ( str_contains("show me how to dance", "show me") )