skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search