PHP key() Function

What is PHP key() Function?

The PHP key() function returns the key or index of the current element where the internal pointer is pointing. Every array has an internal pointer that always points to one array element at any given time. That element is called the current element of that array. When an array is initialized the current pointer is initialized to the first element of the array.

Syntax:

key(array)

Parameters:

The Function has 1 parameter which is required-

array (Required): It is the array whose key of the current element the function looks for.

Return Values:

The function returns key of the current element of the array.

Examples:

Example 1:

<?php
$language = ['PHP', 'Java', 'Python'];
echo "The key(index) of the current element is: " . key($language);
?>

Output:

The key(index) of the current element is: 0

Example 2:

<?php
$language = ['PHP', 'Java', 'Python'];
next($language);next($language);
echo "The key(index) of the current element is: " . key($language);
echo "<br />";
prev($language);
echo "The key(index) of the current element is: " . key($language);
?>

Output:

The key(index) of the current element is: 2
The key(index) of the current element is: 1

Notes on key() Function:

  • If the array is empty which means that there is no element in the array, then, the array returns NULL. Check example .
    <?php
    $language = [];
    echo "The key(index) of the current element is: ";
    var_dump(key($language));
    ?
    

    Output:

    The key(index) of the current element is: NULL

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP key() Function

PHP key() function is built-in PHP array function which is useful to get the current element of your array.

Reference:

https://www.php.net/manual/en/function.key.php