Home    Articles

 

How to get the last key in array with php

 

In order to get the value of the last key from array, you need to use two php functions:

end() - this function will move the array's internal pointer to the last element from array and it will return that value.

key() - this will return the current key ( or the index ) from array where the internal pointer is set.

Here is an example:

$data = array( '3'=>'apple',
            '1'=>'orange',
            '2'=>'strawberry');
// move the pointer
end( $data );
// get the key value
$keyValue = key($data);
echo $keyValue; // 2

But this is not the fastest way to do it. Using array_slice() you can get a faster code.

Here is a new exaple:

$keyValue= key(array_slice($data, -1, 1, TRUE ));
echo $keyValue; // 2

 

by