PHP array_key_exists

Created with Sketch.

PHP array_key_exists

Summary: in this tutorial, you will learn how to use the PHP array_key_exists() function to determine if a key exists in an array.

Introduction to the PHP array_key_exists() function

The PHP array_key_exists() function checks if a key exists in an array. Here’s the syntax of the array_key_exists() function:

array_key_exists ( string|int $key , array $array ) : bool

Code language: PHP (php)

In this syntax:

  • $key is the key to check.
  • $array is an array with keys to check.

The array_key_exists() function returns true if the $key exists in the $array. Otherwise, it returns false.

Note that the array_key_exists() function searches for the key in the first dimension of the $array only. If the $array is multidimensional, the array_key_exists() function won’t find the $key in the nested dimension.

PHP array_key_exists() function example

The following example uses the array_key_exists() function to check if the key 'admin' exists in the $roles array:

<?php

$roles = [
'admin' => 1,
'approver' => 2,
'editor' => 3,
'subscriber' => 4
];

$result = array_key_exists('admin', $roles);

var_dump($result); // bool(true)

Code language: HTML, XML (xml)

The following example returns false because the $roles array doesn’t have the key publisher:

<?php

$roles = [
'admin' => 1,
'approver' => 2,
'editor' => 3,
'subscriber' => 4
];

$result = array_key_exists('publisher', $roles);

var_dump($result); // bool(false)

Code language: HTML, XML (xml)

PHP array_key_exists() vs isset()

If the value of the array element is not null, both array_key_exists() and isset() return true if the key exists in an array and false if it doesn’t. For example:

<?php

$roles = [
'admin' => 1,
'approver' => 2,
'editor' => 3,
'subscriber' => 4
];

var_dump(isset($roles['approver'])); // bool(true)
var_dump(array_key_exists('approver', $roles)); // bool(true)

Code language: HTML, XML (xml)

The following example returns false because the user key doesn’t exist in the $roles array:

<?php

$roles = [
'admin' => 1,
'approver' => 2,
'editor' => 3,
'subscriber' => 4
];

var_dump(isset($roles['user'])); // bool(false)
var_dump(array_key_exists('user', $roles)); // bool(false)

Code language: HTML, XML (xml)

However, if the value of a key is null, the isset() will return false while the array_key_exists() function returns true. For example:

<?php

$post = [
'title' => 'PHP array_key_exists',
'thumbnail' => null
];

var_dump(array_key_exists('thumbnail', $post)); // bool(true)
var_dump(isset($post['thumbnail'])); // bool(false)

Code language: HTML, XML (xml)

Summary

  • Use the PHP array_key_exists() function to check if a key exists in an array.

Leave a Reply

Your email address will not be published. Required fields are marked *