If array_key_exists() is deprecated in PHP7.4, then how to use the alternative like isset() or property_exists() to array?

4.2k views Asked by At

I've already trying array_key_exists(), but when it should return the expected result, lumen display error message that I need to use another php function instead of array_key_exists() like isset() or property_exists() as mentioned in this question title.

$jsonData = "mydata.json";
$content = file_get_contents($jsonData);
$unsortedData = json_decode($content, true);

//convert array to object
$object = (object) $unsortedData;

$key = $request->input('key');
$keyData = "false";
if(array_key_exists($key, $object))
{
    $keyData = "true";
}

// usort($unsortedData,  function($a, $b){
//     return $a['no'] > $b['no'];
// });
return $keyData;
// var_dump($unsortedData);

Which one should be used and how to use it?

3

There are 3 answers

2
Cid On BEST ANSWER

array_key_exists() used to work with objects but that behavior was deprecated in PHP 7.4.0 and removed in PHP 8 :

Note:

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.

To check whether a property exists in an object, property_exists() should be used.

So, you can change your code to :

// Take note that the order of parameters is inverted from the array_key_exists() function
//                    |       |
//                    V       V
if(property_exists($object, $key))
{
    $keyData = "true";
}
0
Genci On

While the above answer solves the issue for some cases, it doesn't when you have protected/private properties.

I used array_key_exists to check if the property was private/protected, where the last ones would be marked with an asterisk by the function and return false, cos the name mismatches.

I solved this like this:

array_key_exists($key, (array)$obj);

So type casting the object should solve it even in php8. I think in php 7 and earlier this was being done under the hood. In 8 they removed it, maybe performance issues??

0
Muhammad Amir On

A lot of people recommending property_exists($object, $key) but it is for objects or class properties not for an array. It will return an error if you check array.

First parameter must either be an object or the name of an existing class