phparraysobjectkeyarray-key-exists

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


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?


Solution

  • 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";
    }