Search code examples
phpstrpos

Why does stripos() !== true always evaluate to true?


Using stripos(), I'm not getting the results I want. I suspect the problem is in the conditional statements. If the condition is true, everything works fine it seems. But if it is false, the code for the condition true still executes. Here's the code.

if (isset($_POST['submit'])) {
    $string = $_POST['sentence'];
    $findString = $_POST['findstring'];
    $strPosition = stripos($string, stringToFind($findString));

    //  if (($strPosition == true) || ($strPosition == 0)) {
    if ($strPosition !== true) {  
        echo 'Found!', '<br><br>';
        echo 'In the string ', $string, '.', '<br>';
        echo 'And the word you want to find is ';
        $readStr = substr($string, $strPosition, strlen($findString));
        echo $readStr, '.', '<br>';

        if ($strPosition == 0) {
            echo 'It is at the beginning of the string.', '<br>';
        } else {
            echo 'It is in the ', $strPosition, ' ', 'position.', '<br>';
        }
    } else {
        echo 'Not found. Try again.', '<br>';
    }
}

function stringToFind($findString)
{
    return $findString = $findString;
}

Solution

  • Yes because your condition gets satisfy even if returns false as you have done a loose comparison with 0. Change your below condition

    if (($strPosition == true) || ($strPosition == 0)) {
    

    with,

    if ($strPosition !== false) {
    

    Helpful: How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?