The basic usage of array_slice is as follows:
array array_slice(array $array, int $offset, ?int $length = null, bool $preserve_keys = false)
$array : The array to operate.
$offset : Start position (can be a negative number, negative number means starting from the end of the array).
$length : The intercepted length (optional).
$preserve_keys : Whether to retain the key name of the original array, the default is false .
To extract the last N elements of the array, the key is to use a negative $offset . If we want to extract the last 3 elements, we can write this:
$lastThree = array_slice($array, -3);
Here, -3 means that the intercept starts from 3 positions to the end of the array and ends up.
<?php
// Example array
$fruits = ["apple", "banana", "orange", "Grape", "mango", "Pineapple"];
// Extract the last 3 Elements
$lastThreeFruits = array_slice($fruits, -3);
print_r($lastThreeFruits);
Output result:
Array
(
[0] => Grape
[1] => mango
[2] => Pineapple
)
Note that by default, array_slice resets the key name of the array, starting from 0. If you want to retain the key name of the original array, you can set the fourth parameter to true :
$lastThreeFruits = array_slice($fruits, -3, null, true);
print_r($lastThreeFruits);
Output:
Array
(
[3] => Grape
[4] => mango
[5] => Pineapple
)
Suppose you have an array of logs that only want to display the latest N logs at a time, you can easily implement them with array_slice :
$logs = [
"2025-05-17 10:00: User login",
"2025-05-17 10:05: User uploads files",
"2025-05-17 10:15: User exit",
"2025-05-17 10:20: User login",
"2025-05-17 10:30: User modification settings",
];
// Show recent 2 Log
$recentLogs = array_slice($logs, -2);
foreach ($recentLogs as $log) {
echo $log . PHP_EOL;
}
Output:
2025-05-17 10:20: User login
2025-05-17 10:30: User modification settings
Suppose we are working on an array containing multiple links and want to get the last few links:
$urls = [
"https://gitbox.net/page1",
"https://gitbox.net/page2",
"https://gitbox.net/page3",
"https://gitbox.net/page4",
"https://gitbox.net/page5",
];
// Get the last two URL
$lastTwoUrls = array_slice($urls, -2);
print_r($lastTwoUrls);
Output:
Array
(
[0] => https://gitbox.net/page4
[1] => https://gitbox.net/page5
)