Search

PHP Check if an Array Key Exists

PHP
post-title

Sometimes you have array key and you want to get value and want to do operation. In that situations, there are few ways you get array value based on key.

isset() method

The fastest way to get key value of array by using isset() method. The isset() method will return false even if array value is null.

<?php

$arr = [null, true];

isset($arr[0]);
# false
isset($arr[1]);
# true

array_key_exists() method

Parameters:
array_key_exists(key, $array) returns true if the key from the $array exists, else it returns false

<?php

$search_array = array('first' => 1, 'second' => null);

array_key_exists('first', $search_array)
# true
array_key_exists('second', $search_array)
# true

array_key_exists() checks if the key exists, even if the value is null.