简体   繁体   中英

array_key_exists error baffling

This is quite possibly NOT something that can be reproduced through a copy & paste. The issue I am having here is that array_key_exists simply is not working.

I have printed my code to the page; it is definitely of type array, not that that is required. The array key exists; I have cast between both string & integer and it is coming back not found.

Now, where it becomes most puzzling is that I have iterated between

$presets    = $this->presets->$name;
echo gettype($version).'<br>';
foreach ( $presets as $key=>$test ) {
    if ( $key===$version ) echo 'string found1<br>';
    elseif ( $key==$version ) echo 'string found2<br>';
}
if ( !array_key_exists($version,$presets) )
    echo 'array_key_exists string fail.<br>';

$version = intval($version);
echo gettype($version).'<br>';
foreach ( $presets as $key=>$test ) {
    if ( $key===$version ) echo 'int found1<br>';
    elseif ( $key==$version ) echo 'int found2<br>';
}
if ( !array_key_exists($version,$presets) )
    echo 'array_key_exists int fail.<br>';

Output:

string
string found1
array_key_exists string fail.
integer
int found2
array_key_exists int fail.

The output is absolutely strange because in both the int & string searches, the key matches. In fact, in the string search, it outputs "string found1", meaning that it === a key within the array. So, then, why is array_key_exists ALWAYS producing FALSE ?

The variable $presets is some array whose indices are created using preg_match regex codes to parse the indices. That is the only added mystery I can come up with, though a manual comparison has proved that an === value was discovered, and therefore none of this should matter. array_key_exists should return TRUE

  Array
  (
      [100] => stdClass Object
          ()
  )

Based on the results you got from $key==$version and $key===$version , we know that the key is a numeric string. So it appears you are using a version of PHP < 7.2.

In those versions, you can't reference a numeric string array key, and array_key_exists will return false whether you give the key in numeric or string form. This confusing behavior was improved with PHP 7.2.

Here's a demo illustrating this, based on the example from this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM