Skip to main content

Oh the treasure of a client coming to you with a site they have removed the previous dev on... treasure hunt.  Not.

Anyway, gaining access to an old site, working through the errors I came across this deprecated code

Deprecated function: array_key_exists(): Using array_key_exists() on objects is deprecated. Use isset() or property_exists() instead in common_check_language() (line 306 of /path/to/file).

 

What has happened and options available

array_key_exists() became deprecated in PHP 7.4.

Options recommended are isset() and property_exists().

 

property_exists()

Checks if the object or class has a property.  Note, property_exists() returns true even if the property has the value null.

isset()

Determine if a variable is declared and is different than null.  Note, isset() will return false when checking a variable that has been assigned to null. 

 

So how do these two options apply to the current code?  Well looking at the code:

/**
 *
 * @param type $obj
 * Object of the page content
 * @param type $field
 * String of a specific field
 *
 * @return type
 * Return as an array
 */
function common_check_language($obj, $field)
{
  $lookup = $obj->$field;
  $language = (array_key_exists(LANGUAGE_NONE, $obj)) ? LANGUAGE_NONE : key($obj->$field);
  return (isset($lookup[$language][0])) ? $lookup[$language][0] : $lookup[$language][1];
}

 

In this instance property_exists) better suits.  So the code now appears as

function common_check_language($obj, $field)
{
  $lookup = $obj->$field;
  $language = (property_exists($obj, LANGUAGE_NONE)) ? LANGUAGE_NONE : key($obj->$field);

  return (isset($lookup[$language][0])) ? $lookup[$language][0] : $lookup[$language][1];
}

 

While there are other areas to clean-up in this code, for now I'm focusing on replacing deprecated array_key_exists() with property_exists() function.

Related articles

Andrew Fletcher29 Sep 2023
How to install PHP 8.1 on Ubuntu 20.04
Update Ubuntu 20.04To begin update the server using the commandsudo apt update && sudo apt upgrade -yFor more details about this process see How To Update All Packages Linux. PHP versionCheck the current PHP version usingphp -vThe response I had wasPHP 7.4.3 (cli) (built: Nov 2...
Andrew Fletcher13 Feb 2023
brew changing PHP versions on OSX
Installing PHP on OSX and it installed PHP 8.2.x.  However, for my applications I need to run 8.1.x.  How do you switch the current PHP version?   Current version Check the current PHP version by executing the command php -v Response: PHP 8.2.2 (cli) (built: Feb ...