How to Get the Last 10 Elements of an Array in PHP?

In PHP, you may often find the need to extract the last 10 elements from an array. This guide illustrates an efficient way to achieve this task. Let's explore the steps to accomplish it.
To retrieve the last 10 elements of a PHP array, you can use a combination of the array_slice()
and count()
functions. Here's a straightforward example:
// Sample PHP array
$data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
// Use array_slice() to extract the last 10 elements
$lastTen = array_slice($data, -10, 10);
// Display the last 10 elements
print_r($lastTen);
In this example, we begin with a PHP array named $data
, which contains a series of numbers. We utilize the array_slice()
function to extract the last 10 elements from the array. The function accepts three arguments: the input array, the starting index (negative to count from the end), and the length (10 in this case).
The output will be an array containing the last 10 elements:
Array
(
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 11
[11] => 12
)