Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unusual string collision in PHP [duplicate]

Tags:

php

I have an array of lower case hex strings. For some reason, in_array is finding matches where none exist:

$x = '000e286592';
$y = '0e06452425';
$testarray = [];
$testarray[] = $x;
if (in_array($y, $testarray)) {
    echo "Array element ".$y." already exists in text array ";
}
print_r($testarray);exit();

The in_array comes back as true, as if '0e06452425' is already in the array. Which it is not. Why does this happen and how do I stop it from happening?

like image 561
Peter Blaskowski Avatar asked Oct 18 '25 03:10

Peter Blaskowski


2 Answers

Odd. This has something to do with the way that PHP compares the values in "non-strict" mode; passing the third argument (strict) as true no longer results in a false positive:

if (in_array($y, $testarray, true)) {
    echo "Array element ".$y." already exists in text array ";
}

I'm still trying to figure out why, technically speaking, this doesn't work without strict checking enabled.

like image 89
esqew Avatar answered Oct 20 '25 18:10

esqew


You can pass a boolean as third parameter to in_array() to enable PHP strict comparison instead of the default loose comparison.

Try this code

$x = '000e286592';
$y = '0e06452425';
$testarray = [];
$testarray[] = $x;
if (in_array($y, $testarray, true)) {
    echo "Array element ".$y." already exists in text array ";
}
print_r($testarray);exit();
like image 25
Mehrdad Moradi Avatar answered Oct 20 '25 18:10

Mehrdad Moradi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!