PHP Function Reference

PHP key() Function



The PHP key() function returns the index element of the current array position.

Syntax

key(array)

Parameters

array Required. Specify the input array.

Return Value

Returns the key of the array element that is currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, it returns null.

Exceptions

NA.

Example:

The example below shows the usage of key() function.

<?php
$Arr = array(10, 20, "Hello", "World");

echo current($Arr)."\n";  //prints 10
echo key($Arr)."\n";      //prints 0
echo next($Arr)."\n";     //prints 20
echo key($Arr)."\n";      //prints 1
echo end($Arr)."\n";      //prints World
echo key($Arr)."\n";      //prints 3

echo "\n";
$Arr1 = array();
var_dump(key($Arr1));     //NULL

$Arr2 = array(array());
var_dump(key($Arr2));     //int(0)
?>

The output of the above code will be:

10
0
20
1
World
3

NULL
int(0)

Example:

Consider one more example where the key() function is used with an associative array.

<?php
$Arr = array(10=>"Red",
             20=>"Green",
             30=>"Blue",
             40=>"Black",
             50=>"White");

echo current($Arr)."\n";  //prints Red
echo key($Arr)."\n";      //prints 10
echo next($Arr)."\n";     //prints Green
echo key($Arr)."\n";      //prints 20
echo end($Arr)."\n";      //prints White
echo key($Arr)."\n";      //prints 50
?>

The output of the above code will be:

Red
10
Green
20
White
50

❮ PHP Array Reference