48

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?

Pradip Kharbuja
  • 3,442
  • 6
  • 29
  • 50
Virus721
  • 8,061
  • 12
  • 67
  • 123

3 Answers3

47

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

akinuri
  • 10,690
  • 10
  • 65
  • 102
Virus721
  • 8,061
  • 12
  • 67
  • 123
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

Vineet1982
  • 7,730
  • 4
  • 32
  • 67
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
Teerath Kumar
  • 488
  • 5
  • 15