phpstring-comparisonstripos

stripos return false on number comparison


I have created a common function which check whether the given string exist in string or not. The function was working fine unless i reached to this problem. The problem is if i pass both find and string to 3 i.e int then it is returning false. I believe it should return true. I read on php official site and found this:

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

Is there any solution to this.

My function is as below:

private static function compareValue($string, $find) {
    if (strpos($find, '!') === 0) {
        //removing first ! for comparison
        $find = substr($find, 1);
        //comparison will be like not equals to
        return !(stripos($string, $find) !== false);
    } else {
        return (stripos($string, $find) !== false);
    }
}

EDIT

if is call function like self::compareValue(3,3) then it should return true instead false.


Solution

  • You can cast to string yourself:

    (string)$find
    

    Feel free to add any check that makes sense for you, since blind casting is not a good idea:

    $find = true;
    var_dump((string)$find);
    
    string(1) "1"