How do you check if an index exists in php?

Is there a way to check if an array index exists or is null? isset[] doesn't tell you whether the index doesn't exist or exists but is null. If I do : isset[$array[$index]] || is_null[$array[$index]] it won't work because if the index doesn't exist is_null will crash.

How can I check this please? Also is there a way to check only if something exist, no matter if it is set to null or not?

asked Mar 9, 2013 at 11:43

4

The function array_key_exists[] can do that, and property_exists[] for objects, plus what Vineet1982 said. Thanks for your help.

akinuri

9,70010 gold badges58 silver badges94 bronze badges

answered Mar 9, 2013 at 12:04

Virus721Virus721

7,7799 gold badges60 silver badges118 bronze badges

4

This is the very good question and you can use get_defined_vars[] for this:

$foo = NULL;
$a = get_defined_vars[];

if [array_key_exists['def', $a]] {
   // Should evaluate to FALSE
 }; 

if [array_key_exists['foo', $a]] {
   // Should evaluate to TRUE
};

This will solve your problem

answered Mar 9, 2013 at 12:02

Vineet1982Vineet1982

7,5824 gold badges29 silver badges65 bronze badges

1

[PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8]

array_key_existsChecks if the given key or index exists in the array

Description

array_key_exists[string|int $key, array $array]: bool

Parameters

key

Value to check.

array

An array with keys to check.

Return Values

Returns true on success or false on failure.

Note:

array_key_exists[] will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found.

Examples

Example #1 array_key_exists[] example

Chủ Đề