PHP Arrays Checking if a Key Is in an Array - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Arrays Checking if a Key Is in an Array - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Saturday, May 18, 2019

PHP Arrays Checking if a Key Is in an Array

PHP Arrays



Checking if a Key Is in an Array

Problem

You want to know if an array contains a certain key.

Solution

Use array_key_exists() to check for a key no matter what the associated value is:

             if (array_key_exists('key', $array)) {
             /* there is a value for $array['key'] */
             }

Use isset() to find a key whose associated value is anything but null:
           
             if (isset($array['key'])) { /* there is a non-null value for 'key' in $array */ }

Discussion

The array_key_exists() function completely ignores array values—it just reports whether there is an element in the array with a particular key. isset(), however, behaves the same way on array keys as it does with other variables. A null value causes is set() to return false. 



No comments:

Post a Comment

Post Top Ad