Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last key in an array?

Tags:

arrays

php

How can I get the last key of an array?

like image 208
ajsie Avatar asked Feb 27 '10 17:02

ajsie


People also ask

How do I get the last key of an array?

The end() function is an inbuilt function in PHP and is used to find the last element of the given array. The end() function changes the internal pointer of an array to point to the last element and returns the value of the last element.

Is last element of array PHP?

You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.

How do you find the last and first element in an array?

To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.

How do you find array keys?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. Specified array.


1 Answers

A solution would be to use a combination of end and key (quoting) :

  • end() advances array 's internal pointer to the last element, and returns its value.
  • key() returns the index element of the current array position.

So, a portion of code such as this one should do the trick :

$array = array(     'first' => 123,     'second' => 456,     'last' => 789,  );  end($array);         // move the internal pointer to the end of the array $key = key($array);  // fetches the key of the element pointed to by the internal pointer  var_dump($key); 

Will output :

string 'last' (length=4) 

i.e. the key of the last element of my array.

After this has been done the array's internal pointer will be at the end of the array. As pointed out in the comments, you may want to run reset() on the array to bring the pointer back to the beginning of the array.

like image 98
Pascal MARTIN Avatar answered Oct 22 '22 13:10

Pascal MARTIN