2

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.

Curious
  • 93
  • 1
  • 11
  • just make sure they are always string `$string + ""` and `$find + ""` – Edwin Aug 22 '18 at 11:07
  • 1
    When it says *ordinal value of a character* - https://stackoverflow.com/questions/19174563/what-is-an-ordinal-value-of-a-string – Nigel Ren Aug 22 '18 at 11:11

2 Answers2

2

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"
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
2

If I'm not mistaken, stripos is for strings so you should be casting the integer to a string. Notice that you only need to cast it in the else statement as if it falls under the first condition it is already a string.

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, (string)$find) !== false);
    }
}
Pedro Caseiro
  • 485
  • 2
  • 11