Search code examples
phpif-statementstrstr

PHP: Why do we use stristr() as a condition in an 'if' statement when its return type is string, not bool?


The question is from a statement from a piece of code from here (the last PHP program on the page) The statement is:

if (stristr($q, substr($name,0,$len))) {...}

But according to the manual, the return type of stristr() is string. It returns a string, not a bool, so how can we use it in an if statement?


Solution

  • PHP, like most programming languages evaluates the conditional expression (the code inside an if statement) to a boolean expression:

    if (123)
        echo '123 is true';
    

    This will echo the text because, when it comes to ints, everything except 0 is true (or truthy as it is also known).
    You can check the official documentation here to get a detailed overview of what types/values evaluate to true and which to false.

    Of course, in the case of strstr and stristr, when no substring is found, the function will actually return false, and so a type and value check of the return value is not uncommon:

    if (stristr($string, 'needle') !== false)
        echo 'The needle was found';