How do I Get the Last Key of an Array in PHP?

Mary-Kate Olsen
Release: 2024-11-06 09:33:02
Original
526 people have browsed it

How do I Get the Last Key of an Array in PHP?

Retrieving the Last Array Key

This question revolves around obtaining the last key in an array.

Solution:

A practical approach involves the combined usage of PHP's end() and key() functions.

  • end() advances the internal array pointer to the last element, providing its value.
  • key() retrieves the index of the element pointed to by the current internal pointer.

Subsequently, the following code exemplifies this:

<code class="php">$array = array(
    'first' => 123,
    'second' => 456,
    'last' => 789,
);

end($array);         
$key = key($array);  

var_dump($key);</code>
Copy after login

This code will output:

<code class="php">string 'last' (length=4)</code>
Copy after login

indicating the last key in the given array.

It's important to note that the internal pointer will remain at the end of the array after this operation. Consider using reset() to return the pointer to the beginning if desired.

The above is the detailed content of How do I Get the Last Key of an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!