How to know if a certain array key exists in an associative array in PHP

In most PHP frameworks or any basic MVC systems, you are probably using a lot more, if not completely exclusively, associative arrays to send data to classes and their methods, to databases, and receiving data back from libraries interacting with databases that will provide your scripts in an associative array format. The key/value pairing is a staple in database and systems, it makes the most sense in most applications.

There might come a time when you need to know if a certain array key exists, so if it was returned you could then act on it. This is similar to the “stristr()” function for strings, or a close neighbor to the “in_array()” function for array values. The point is, you need to sometimes look in order to act and the lack of an array key in some object’s method’s results might be vital information your script needs to continue, redirect, or stop based on such conditions.

As easy as it sounds, I have seen a lot of code written that loops through each array element to manually check if a key was set, then breaking the loop once found. PHP has a function built right in, so get rid of all that code and simply use “array_key_exists()”!

// Old code from someone who didn't discover PHP.net or just wanted to overcomplicate things to create "job security":

$foundKey=false;
foreach($search_array as $key=>$val){
if ($key=='keyToFind'){
$foundKey=true;
break;
}
}

// Or, just use the built in function the great folks at PHP created:
array_key_exists('keyToFind', $search_array);

Visit http://php.net/manual/en/function.array-key-exists.php for more information.

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *