PHP - Checking if array index exist or is null [duplicate]
Asked Answered
D

3

49

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?

Doi answered 9/3, 2013 at 11:43 Comment(1)
Wouldn't the same if statements in a nested if structure work fine?Gerik
D
49

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

Doi answered 9/3, 2013 at 12:4 Comment(4)
Using array_key_exists() on objects is deprecated.Zerk
@Zerk No one said one should do that. And this question is 8 years old, so obviously things evolve.Doi
Yes. That is why I mentioned it. And it didn't work in my case. So,..Zerk
This answer is still valid in 2022. array_key_exists for arrays (not objects), property_exists for objects.Babbie
B
22

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

Bureaucratic answered 9/3, 2013 at 12:2 Comment(1)
Ok but add the array_key_exist thing in it thenDoi
E
11

Simplest defined in: http://php.net/manual/en/function.array-key-exists.php

<?php
$array=array('raja'=>'value', 'john'=>'value2');
$var='raja';
echo array_key_exists($var, $array);
?>

OR

<?php
$array=array('raja'=>'value', 'john'=>'value2');

echo isset($array['raja']) ? "exists" : "does not exist";
?>
//Output: exists
Excaudate answered 23/7, 2015 at 7:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.