1.2.500. Getting Last Element

Getting the last element of an array relies on array_key_last().

array_key_last() was added in PHP 7.3. Before that, other ways had to be used, such as reaching the count() - 1 elements, or via array_pop(`array_keys()) <https://www.php.net/array_keys>`_.

<?php

$array = ['a' => 1, 'b' => 2, 'c' => 3];

// Best solutions, by far
$last = $array[array_key_last($array)];

// Best solutions, just as fast as each other
$last = $array[count($array) - 1];
$last = end($array);

// Bad solutions

// popping, but restoring the value.
$last = array_pop($array);
$array[] = $last;

// array_unshift would be even worse

// reversing array
$last = array_reverse($array)[0];

// slicing the array
$last = array_slice($array, -1)[0]',
$last = current(array_slice($array, -1));
);

?>

1.2.500.1. Suggestions

  • Use PHP native function : array_key_last(), when using PHP 7.4 and later

  • Use PHP native function : array_pop()

  • Organise the code to put the last element in the first position (array_unshift() instead of append operator [])

1.2.500.2. Specs

Short name

Arrays/GettingLastElement

Rulesets

All, Changed Behavior, Performances

Exakat since

0.9.0

PHP Version

All

Severity

Minor

Time To Fix

Instant (5 mins)

Precision

High

Features

array

Examples

Thelia

Available in

Entreprise Edition, Exakat Cloud