0

I use in_array to search a number in an array. When I searched 084 I got true. After that I searched for 84, but I got true and "084" value.

How can I avoid that?

This is the code where the check is made:

if (in_array(strval($_GET['search']), $vall))
{
    array_push($allwin,$number_array[0][0]);
}

The array I'm testing on is extracted from JSON that has values like these:

["\u0e40\u0e25\u0e02\u0e17\u0e49\u0e32\u0e223\u0e15\u0e31\u0e27","084","375"]

1 Answer 1

4

Because numerically, 084 and 84 both present the same number. Since by default in_array uses loose comparison, it will match them, as it will internally apply type conversion and both will be converted to 84, as they are numeric.

If you look at the in_array documentation, you will see it has a third parameter:

in_array ( mixed $needle , array $haystack , bool $strict = false ) : bool

which determines whether loose or strict comparison should be used. Setting it to true would give you the desired result.

For example, if you were to run the following commands:

var_dump(in_array(84, ['084', '756', '34']));
var_dump(in_array(84, ['084', '756', '34'], true));
var_dump(in_array('84', ['084', '756', '34'], true));
var_dump(in_array('084', ['084', '756', '34'], true));

they would output:

true // loose comparison, 84 == '084', both cast to numbers resulting in 84 being compared to 84
false // strict comparison, 84 !== '84', as one is int and the other string
false // strict comparison, '84' !== '084', as they're not identical strings, the second one has an extra character at the beginning
true // strict comparison, '084' === '084', identical strings
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.