Home > Article > Backend Development > How to Retrieve the Last Key of an Array in PHP?
Retrieving the Last Key from an Array
In programming, it can be necessary to obtain the last key of an array. This key represents the index of the last element within the array. To accomplish this, one effective approach utilizes the combination of end() and key() functions.
end() Function:
The end() function advances the internal pointer of an array to point to the last element. It does not return any value.
key() Function:
The key() function obtains the index of the element currently pointed to by the internal pointer.
Combining end() and key():
To get the last key of an array, you can use the following steps:
Example Code:
<code class="php">$array = [ 'first' => 123, 'second' => 456, 'last' => 789, ]; end($array); // Move the internal pointer to the end of the array $key = key($array); // Get the key of the last element var_dump($key);</code>
This code will output:
string 'last' (length=4)
indicating that the key of the last element is 'last'.
Note: After using end() and key(), the internal pointer will be at the end of the array. To reset it to the beginning, you can use the reset() function.
The above is the detailed content of How to Retrieve the Last Key of an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!