PHP check if key exists in array

Checking if a key exists in an array and possibly has a non empty value are frequently used when writing php code. Accessing value of non existing key can throw php errors in some cases. Here are some examples which can be used in various scenarios without any php error/notice in log.

array_key_exists example

array_key_exists() checks for only presence of key irrespective of its value which may be 0 or null.

<?php
$a = array("key1"=>"val1", "key2"=>"");
if (array_key_exists('key2', $a)) {
  echo "key2 EXISTS\n";
} else {
  echo "key2 DOES_NOT_EXIST\n";
}
?>
key2 EXISTS
Env: PHP 5.5.9 (Linux)

isset() check on key value

isset() checks is similar to array_key_exists but fails if key value is null. This may be useful in some cases to make code compact and more readable. Also using !is_null() is similar but generates PHP warning. So its better to avoid it.

<?php
$a = array("key1"=>"val1", "key2"=>null);
if (isset($a['key1'])) {
  echo "key1 value is set\n";
} else {
  echo "key1 value is not set\n";
}
if (isset($a['key2'])) {
  echo "key2 value is set\n";
} else {
  echo "key2 value is not set\n";
}
?>
key1 value is set
key2 value is not set
Env: PHP 5.5.9 (Linux)

!isempty() check on key value

isempty() checks if key value is empty. This is useful in many cases to make code compact and more readable.

<?php
$a = array("key1"=>"val1", "key2"=>"");
if (!empty($a['key1'])) {
  echo "key1 value is not empty\n";
} else {
  echo "key1 value is empty\n";
}
if (!empty($a['key2'])) {
  echo "key2 value is not empty\n";
} else {
  echo "key2 value is empty\n";
}
?>
key1 value is not empty
key2 value is empty
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments