Home >Backend Development >PHP Tutorial >How to Retrieve the Last Key in a PHP Array?
In the realm of PHP arrays, accessing the last key can be a useful task. This guide will explore how to accomplish this with a combination of the end() and key() functions:
Understanding the Approach:
Code Snippet:
Consider the following portion of code as an example:
<code class="php">$array = array( 'first' => 123, 'second' => 456, 'last' => 789, // Last element in the array ); end($array); // Move the pointer to the last element $key = key($array); // Capture the key of the last element var_dump($key); // Output: 'last'</code>
Explanation:
By calling end() on the $array, the internal pointer is positioned at the last element with a value of 789. Subsequently, using key(), we retrieve the key associated with this element, which is 'last'. This key is the last key in the array.
Note:
After retrieving the last key, the internal pointer remains at the end of the array. To reset the pointer to the beginning, consider using the reset() function.
The above is the detailed content of How to Retrieve the Last Key in a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!