How to Retrieve the Last Key of an Array in PHP?

Patricia Arquette
Release: 2024-11-06 17:08:02
Original
287 people have browsed it

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:

  1. Call end() to move the internal pointer to the last element.
  2. Call key() to retrieve the index of the element at the end of the array.

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>
Copy after login

This code will output:

string 'last' (length=4)
Copy after login

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!

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!