The following article indicates the differences between the two inbuilt functions array_keys() and array_key_exists() in PHP.
array_keys() Function: The array_keys() function is used to return all the keys or a subset of the array keys. This function works for both indexed as well as associative arrays.
Syntax:
array_keys(array, value, strict)
Parameters:
- array: An array with keys to check.
- value: The value to retrieve the keys for.
- strict: The parameter to check the data type of the variable or not.
Example 1:
PHP
<?php $arr = array ( "Java" => "SpringBoot" , "PHP 4.0" => "CodeIgniter" , "Python" => "Django" , "PHP 3.0" => "CodeIgniter" ); // Searching for keys of codeigniter $key1 = array_keys ( $arr , "CodeIgniter" ); print ( "Keys for CodeIgniter : " ); print_r( $key1 ); print ( "</br>" ); // Searching for keys of wordpress $key2 = array_keys ( $arr , "WordPress" ); print ( "Keys for WordPress : " ); print_r( $key2 ); ?> |
Output:
Keys for CodeIgniter : Array ( [0] => PHP 4.0 [1] => PHP 3.0 ) Keys for WordPress : Array ( )
Example 2:
PHP
<?php $arr = array (1, 2, 3, 4, 5); // Searching for keys of string 5 // using strict parameter true $key1 = array_keys ( $arr , "5" , true); print ( "Keys for '5' : " ); print_r( $key1 ); echo ( "</br>" ); // Searching for keys of string 5 // using strict parameter false $key2 = array_keys ( $arr , "5" , false); print ( "Keys for '5' : " ); print_r( $key2 ); ?> |
Output:
Keys for '5' : Array ( ) Keys for '5' : Array ( [0] => 4 )
array_key_exists(): 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:
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
Differences: The following differences exist between the two mentioned methods:
array_keys | array_key_exists |
---|---|
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. |