Recipe 4.10. Checking if a Key Is in an Array

4.10.1. Problem

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

4.10.2. 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 */ }

4.10.3. 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 isset( ) to return false. See the Introduction to Chapter 5 for more information about the truth value of variables.

4.10.4. See Also

Documentation on isset( ) at and on array_key_exists( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: