Skip to content

Core\Arr::reverse

Core\Arr::reverse(array<T> $a, {preserveKeys?: bool}): array<T>Core\Arr::reverse(
    array<T> $a,
    {preserveKeys?: bool},
): array<T>

Gives you the entries of an array in the opposite order.

The result is a new array, and the original is not changed. By default the keys of the original are gone: the entries are numbered from 0, string keys included. Set preserveKeys to keep every entry under its own key. The values come back in the same order either way, and only the keys differ.

Good to know: a list you reverse twice is the list you started with. An array with keys you reverse twice has its values in the original order again, and the keys are gone unless you asked to keep them.

Parameters

  • $aarray<T>The array to reverse.

Options

  • preserveKeysbooloptionalKeeps every entry's own key. By default every key is discarded, string keys included, and the result is renumbered from "0".

Return value

Returns array<T>. The same entries, last first.

Examples

Newest first

<?nvs
// Shows the entries of a list in the opposite order.
array<string> $steps = ['packed', 'shipped', 'delivered'];
// `Core\Arr::reverse` returns a new array with the entries in the opposite
// order. This prints ["delivered","shipped","packed"].
echo Core\Json::encode(Core\Arr::reverse($steps)), "\n";
// The original array is not changed. This prints ["packed","shipped","delivered"].
echo Core\Json::encode($steps), "\n";
Output
["delivered","shipped","packed"]
["packed","shipped","delivered"]

The keys of the result

<?nvs
// Shows which keys the result carries.
array<int> $stock = ['apples' => 12, 'pears' => 4, 'plums' => 7];
// The keys of the original are gone, and the entries are numbered from 0. This
// prints [7,4,12].
echo Core\Json::encode(Core\Arr::reverse($stock)), "\n";
// `preserveKeys` keeps every entry under its own key. This prints
// {"plums":7,"pears":4,"apples":12}.
echo Core\Json::encode(Core\Arr::reverse($stock, { preserveKeys: true })), "\n";
// Reversing twice gives you the values in the order you started with. This
// prints [12,4,7].
echo Core\Json::encode(Core\Arr::reverse(Core\Arr::reverse($stock))), "\n";
Output
[7,4,12]
{"plums":7,"pears":4,"apples":12}
[12,4,7]

A breadcrumb trail

<?nvs
// Shows a breadcrumb trail on a shop page. The trail is collected from the page
// upwards, so it is reversed before it is printed.
array<string> $parent = ['Running shoes' => 'Shoes', 'Shoes' => 'Clothing'];
array<string> $trail = ['Running shoes'];
string $at = 'Running shoes';
while (Core\Arr::hasKey($parent, $at)) {
$at = $parent[$at];
$trail[] = $at;
}
// `$trail` reads from the page upwards. Reversing it puts the top level first.
// This prints "Clothing > Shoes > Running shoes".
echo Core\Str::join(Core\Arr::reverse($trail), ' > '), "\n";
Output
Clothing > Shoes > Running shoes