Skip to content

Core\Arr::prepend

Core\Arr::prepend(array<T> $a, T ...$values): array<T>Core\Arr::prepend(
    array<T> $a,
    T ...$values,
): array<T>

Adds one or more values to the front of an array.

Core\Arr::prepend never changes the array you give it. It returns a new array: first each value you added, in the order you wrote them, then every value of your array.

The result is always a list. Its keys are numbers again, counting from "0", and the keys your array had are gone. A value put in front of the first entry has no key of its own, and "0" may already be in use, so Novis numbers the whole result instead of choosing a key for you. This is the one place where adding at the front and adding at the end differ.

If you pass no value, the result is your array with its keys renumbered.

Parameters

  • $aarray<T>The array to put them in front of.
  • ...$valuesTvariadicThe values to put in front, in written order.

Return value

Returns array<T>. A list renumbered from "0". Every key is discarded, because a value put in front has no key of its own.

Examples

Put one task first

<?nvs
// Shows how to put one value at the front of a list.
array<string> $tasks = ['pack the order', 'print the label'];
// `Core\Arr::prepend` returns a new array. Your own array stays as it was.
array<string> $today = Core\Arr::prepend($tasks, 'call the customer');
// This prints the new task first, then the other two.
foreach ($today as string $task) {
echo $task, "\n";
}
// `$tasks` still has two entries, so this prints 2.
echo Core\Arr::count($tasks), "\n";
Output
call the customer
pack the order
print the label
2

Several values and the new keys

<?nvs
// Shows how to add several values in one call, and what happens to the keys.
array<string> $labels = ['de' => 'Deutsch', 'fr' => 'Français'];
// The values are added in the order you write them.
array<string> $withEnglish = Core\Arr::prepend($labels, 'English', 'Español');
// The result is a list, so this prints 0, 1, 2 and 3.
foreach (Core\Arr::keys($withEnglish) as string $key) {
echo $key, "\n";
}
// The values keep their order: English, Español, Deutsch, Français.
echo Core\Str::join($withEnglish, ', '), "\n";
Output
0
1
2
3
English, Español, Deutsch, Français

An all entry for a filter menu

<?nvs
// Shows how a shop builds the filter menu above a product list. The categories
// come from storage, and the menu needs an entry for "all of them" at the top.
array<string> $categories = ['Shoes', 'Bags', 'Hats'];
array<string> $menu = Core\Arr::prepend($categories, 'All products');
// This prints the four entries with their position, starting at 0.
foreach ($menu as string $key => string $entry) {
echo $key, ': ', $entry, "\n";
}
Output
0: All products
1: Shoes
2: Bags
3: Hats