Computer >> Computer tutorials >  >> Programming >> PHP

key() function in PHP


The key() function fetches a key from an array. It returns the key of the array element pointed by the internal pointer.

Syntax

key(arr)

Parameters

  • arr − The array to be used.

Return

The key() function returns the key of the array element pointed by the internal pointer.

Example

The following is an example −

<?php
$arr = array("Electronics","Footwear");
echo "Key from the current position = " . key($arr);
?>

Output

Key from the current position = 0

Example

Let us see another example −

<?php
$arr = array(
'one' => 'tim',
'two' => 'peter',
'three' => 'david');
while ($val = current($arr)) {
   if ($val == 'peter') {
      echo key($arr);
   }
   next($arr);
}
?>

Output

two