Joren
Joren

Reputation: 9915

Get the last element of an array without changing the array in PHP?

array_pop() removes it from the array. end() changes the internal pointer.

Is the only way really some cludge like:

$my_array[array_pop(array_keys($my_array))];

?

Upvotes: 10

Views: 5817

Answers (6)

White Crown
White Crown

Reputation: 56

  1. Get last key:
$last_key = array_key_last($my_array); //Get the last key of the given array without affecting the internal array pointer.
  1. Get last element:
echo $my_array[$last_key];

Upvotes: 0

Bedder
Bedder

Reputation: 1

<?php
/**
 * Return last element from array without removing that element from array.
 * https://github.com/jdbevan/PHP-Scripts/
 * 
 * @param array $array The array to get the last element from
 * @return mixed False if $array is not an array or an empty array, else the key of the last element of the array.
 */ 
function array_peek($array) {
    if (!is_array($array)) return false;
    if (count($array)<1) return false;

    $last_key = array_pop(array_keys($array));
    return $array[$last_key];
}
?>

Upvotes: 0

LibraryThingTim
LibraryThingTim

Reputation: 433

Unfortunately

list($end) = array_slice($array, -1);

doesn't work with associative arrays. So I use

function pop_array_nondestructive( $array )
    {
    return end($array);
    }

Upvotes: 0

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99889

This works:

list($end) = array_slice($array, -1);

array_slice($array, -1) returns an array with just the last element and list() assigns the first element of slice's result to $end.

@Alin Purcaru suggested this one in comments:

$end = current(array_slice($array, -1));

Since PHP 5.4, this works too:

array_slice($array, -1)[0]

Upvotes: 25

Your Common Sense
Your Common Sense

Reputation: 157839

end($my_array);

I see nothing bad in changing internal pointer. Nobody is using it these days anyway

Upvotes: -6

Alin P.
Alin P.

Reputation: 44346

Erm... what about reset()ting after you use end()?

$lastItem = end($myArr);
reset($myArr);

Upvotes: 3

Related Questions