array_key_exists() Function
The array_key_exists() method in PHP is used to validate an array for a specified key. It returns a boolean value of “true” if the key exists and “false” if the key does not exist in the array.
Syntax
array_key_exists(key, array);
Parameters
- key: The values to check.
- array: An array with keys to check.
Example 1: This example illustrates the basic usage of the array_key_exists() Function in PHP.
PHP
<?php $arr = array (1, 2, 3, 4, 5); // Searching for keys of string 5 $key1 = array_key_exists ( '4' , $arr ); if ( $key1 ) { echo ( "Key exists" ); } else { echo ( "Key does not exist" ); } ?> |
Output:
key exists
Example 2: This example demonstrates the array_key_exists() function in PHP based on some key in the array holding key-value pairs.
PHP
<?php $myarray = array ( "ram" => 25, "krishna" => 10, "aakash" => 20, "gaurav" ); // Searching for keys $key1 = array_key_exists ( 'krishna' , $myarray ); if ( $key1 ) { echo ( "Key exists" . " for 'krishna'" ); } else { echo ( "Key does not exist" ); } print_r( "<br>" ); $key2 = array_key_exists ( 'balram' , $myarray ); if ( $key2 ) { echo ( "Key exists" . " for 'balram'" ); } else { echo ( "Key does not exist" . " for 'balram'" ); } ?> |
Output:
Key exists for 'krishna'
Key does not exist for 'balram'
Example 3: This example demonstrates the array_key_exists() function in PHP based on the $index value by the user.
PHP
<?php $myarray = array ( "ram" , "krishna" , "aakash" , "gaurav" ); $index1 = 1; $key1 = array_key_exists ( $index1 , $myarray ); if ( $key1 ) { echo ( "Key exists for index " . $index1 ); } else { echo ( "Key does not exist for index " . $index1 ); } print_r( "<br>" ); $index2 = 5; $key2 = array_key_exists ( $index2 , $myarray ); if ( $key2 ) { echo ( "Key exists for index " . $index2 ); } else { echo ( "Key does not exist for index " . $index2 ); } ?> |
Output:
Key exists for index 1
Key does not exist for index 5
Differences between the array_keys() and array_key_exists() Methods
array_keys() Methods |
array_key_exists() Methods |
---|---|
It checks if the corresponding value is mapped to any key in the array. | It checks if a key exists in the array. |
It returns an array. | It returns a boolean value. |
It works for both uni and multi-dimensional arrays. | It works only for uni-dimensional arrays. |
It can be used to match data type using strict parameter | It can be used to match the only value |
It can also be used to retrieve all the keys of the array if the value parameter is blank. | It simply checks for the specified key in the array. |
What are the differences between array_keys() and array_key_exists() in PHP ?
The following article indicates the differences between the two inbuilt functions array_keys() and array_key_exists() in PHP.