Search code examples
phpfunctionstrpos

Why does comparing the return value from strpos() with !== TRUE always true?


I created custom function OutputMessage from where I'm inserting error message with its ClassStyle like this Error: image upload failed! and then I'm exploding string and split class from it add in to div class but my function is not working fine.

function OutputMessage($Message=''){
    if($Message){
        $Postion = strpos($Message,":");
        if($Postion !== TRUE){
            return sprintf('<div class="alert alert-default">%s</div>',$Message); 
        }else{
            $Message = explode(": ",$Message);
            return sprintf('<div class="alert alert-%s">%s</div>',strtolower($Message[0]),$Message[1]); 
        }
    }else{
        return "";
    }
}

$Position check is not working because I'm passing Message with it's class but it's still returning default class.


Solution

  • From the manual entry of strpos() function:

    Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

    Returns FALSE if the needle was not found.

    which means that if($Postion !== TRUE) will always be true, as strpos() never returns true.

    To make your function work as expected, change your if statement to if($Postion === false).