Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concerns about array-key-exists Function During PHP 8.x Upgrade

I am upgrading the PHP version for the system from PHP 7.3x to 8.x.
According to the documentation at https://www.php.net/manual/en/function.array-key-exists.php, it states that in version 8.x, array-key-exists will be removed.

However, in practice, when I tested it using https://onlinephp.io/c/318c8, array-key-exists still works.

Therefore, is it necessary to switch from array-key-exists to property_exists?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From the manual:

For backward compatibility reasons, array_key_exists() will also
return true if key is a property defined within an object given as
array. This behaviour is deprecated as of PHP 7.4.0, and removed as of
PHP 8.0.0.

This does not mean that array_key_exists() itself is removed. This is referring only to the use case where the thing being tested is an object and not an array. An object cast to array, either explicitly via (array) $obj or implicitly via context will yield an associative array of the public attributes of the object. For example:

$obj = new stdClass();
$obj->foo = 'bar';
print_r((array) $obj);

This outputs:

Array
(
    [foo] => bar
)

So, you can do this:

if (array_key_exists('foo', $obj)) { // $object is implicitly cast to array here
    // this condition fires because the key exists in the cast array
}

If versions prior to 7.4, this works fine. In 7.4, it works but generates a deprecation warning. In 8.0 and after, it generates an error.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading