Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Checking if array index exist or is null

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?

like image 576
Virus721 Avatar asked Mar 09 '13 11:03

Virus721


People also ask

How do I check if an index exists in an array?

PHP: Checks if the given key or index exists in an array The array_key_exists() function is used to check whether a specified key is present in an array or not. The function returns TRUE if the given key is set in the array. The key can be any value possible for an array index.

How do you check if an index exists in PHP?

The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false.


2 Answers

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

like image 122
Virus721 Avatar answered Sep 30 '22 01:09

Virus721


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

like image 22
Vineet1982 Avatar answered Sep 30 '22 02:09

Vineet1982