Home  >  Article  >  Backend Development  >  How to Retrieve the Last Key of an Array in PHP?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 17:08:02288browse

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>

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!

Statement:
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