Open In App

PHP array_key_exists() Function

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The array_key_exists() function in PHP is a built-in function that checks whether a specified key exists in an array. This function is commonly used when working with associative arrays, where keys are explicitly defined, and we need to confirm the presence of a particular key to prevent errors or undesired behaviors when accessing array values.

Syntax

bool array_key_exists($index, $array)

Parameters

This function accept two paramters that are described below:

  • $index: This parameter is mandatory and refers to the key that is needed to be searched for in an input array.
  • $array: This parameter is mandatory and refers to the original array in which we want to search the given key $index.

Return Value: This function returns a boolean value i.e., TRUE and FALSE depending on whether the key is present in the array or not respectively.

Note: Nested keys will return the FALSE result. 

Example 1: This program illustrates the array_key_exists() function to find a key inside an array that holds key_value pair.

PHP
<?php

// PHP function to illustrate the use
// of array_key_exists()
function Exists($index, $array) {
    if (array_key_exists($index, $array)) {
		echo "Found the Key";
    } else {
		echo "Key not Found";
    }
}

$array = array(
    "ram" => 25,
    "krishna" => 10,
    "aakash" => 20,
    "gaurav"
);

$index = "aakash";
print_r(Exists($index, $array));

?>

Output
Found the Key

If no key_value pair exits, as shown in the below case, then the array takes the default keys i.e. numeric keys starting from zero, into consideration and returns true as far as the $index limit ranges.

Example: This example illustrates the array_key_exists() function in PHP by specifying the particular $index value.

PHP
<?php

// PHP function to illustrate the use of
// array_key_exists()
function Exists($index, $array) {
	if (array_key_exists($index, $array)) {
		echo "Found the Key";
	} else {
		echo "Key not Found";
    }
}   

$array = array(
    "ram",
    "krishna",
    "aakash",
    "gaurav"
);

$index = 2;
print_r(Exists($index, $array));

?>

Output
Found the Key

Referencehttp://php.net/manual/en/function.array-key-exists.php


Next Article

Similar Reads