PHP key() Function

PHP key() Function

The key() function in PHP fetches a key from an array and returns the index element of the current array position.

Syntax

key ( array $array )

Parameter

array(required)- This parameter represents the input array.

Return

This function returns the key of the array element that's currently being pointed to by the internal pointer.  It returns null If the internal pointer points beyond the end of the elements list or the array is empty.

Example 1

 'apple',2 => 'orange', 3 => 'grape', 4 => 'apple', 5 => 'mango');
 //will return the key value of the current pointer
  echo "The current pointer is at ".key($array)." key.\n";//will return 1
 ?> 

Output

The current pointer is at 1 key.

Example 2

 'apple',2 => 'orange', 3 => 'grape', 4 => 'apple', 5 => 'mango');
 //will return the pointer to the end of the array
 end($array);
 //will return the key value of the current pointer
  echo "The current pointer is at ".key($array)." key.\n";//will return 5
 ?> 

Output

The current pointer is at 5 key.

Example 3

 

Output

PHP Warning:  key() expects parameter 1 to be array, null given in /workspace/Main.php on line 5