Home > Back-end >  lumen array_key_exists() depreciated, then how to use the alternative like isset() or property_exist
lumen array_key_exists() depreciated, then how to use the alternative like isset() or property_exist

Time:10-22

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);

so, which one should be used and how to use it? thanks for your help

CodePudding user response:

array_key_exists() can work with objects but that behavior is 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";
}
  • Related