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