Skip to content

Core\Arr::withoutLast

Core\Arr::withoutLast(array<T> $a): array<T>Core\Arr::withoutLast(
    array<T> $a,
): array<T>

Returns a new array with every entry except the last one.

Core\Arr::withoutLast never changes the array you give it. Every entry that stays keeps its own key, so a list keeps the numbering it had and only its highest key is gone.

Core\Arr::last returns the value this method leaves out. Use the two together when you want to read the newest value and then continue with the ones before it.

Good to know: an array with one entry gives an empty array, and an empty array gives an empty array. Both are normal results, and neither is an error.

Parameters

  • $aarray<T>The array to shorten.

Return value

Returns array<T>. The remaining entries under their own keys, never renumbered; the empty array for an array of one entry or none.

Examples

Everything before the newest

<?nvs
// Shows how to remove the newest value from a list.
array<string> $history = ['home', 'products', 'cart'];
// `Core\Arr::withoutLast` returns a new array with the first two pages.
array<string> $back = Core\Arr::withoutLast($history);
// This prints "home" and "products".
foreach ($back as string $page) {
echo $page, "\n";
}
// Your own array is not changed, so this prints 3.
echo Core\Arr::count($history), "\n";
Output
home
products
3

An array with text keys

<?nvs
// Shows the result for an array whose keys are words. Every entry that stays
// keeps its own key.
array<int> $scores = ['ada' => 9, 'ben' => 7, 'cleo' => 8];
array<int> $earlier = Core\Arr::withoutLast($scores);
// This prints "ada 9" and "ben 7".
foreach ($earlier as string $name => int $score) {
echo $name, ' ', $score, "\n";
}
Output
ada 9
ben 7

A breadcrumb line

<?nvs
// Shows how to build a breadcrumb line. The last part is the page the reader
// is on. The parts before it are the pages above it.
array<string> $trail = ['Shop', 'Shoes', 'Running shoes'];
array<string> $above = Core\Arr::withoutLast($trail);
// This prints "Shop > Shoes".
echo Core\Str::join($above, ' > '), "\n";
// This prints 2, so you know how many links to write.
echo Core\Arr::count($above), "\n";
Output
Shop > Shoes
2