Skip to content

Core\Arr::appendAll

Core\Arr::appendAll(array<T> $a, array<U> ...$others): array<T|U>Core\Arr::appendAll(
    array<T> $a,
    array<U> ...$others,
): array<T|U>

Joins arrays end to end, and numbers the result from 0.

You give a first array and as many more as you like. The result holds every value of the first array, then every value of the second, and so on, in that order. The keys the arrays had are not kept: the result is always a list. Nothing is compared and nothing is dropped, so a value that is in two of the arrays is in the result twice.

Good to know: use Core\Arr::overlay when the keys matter and a later value should replace an earlier one with the same key.

Parameters

  • $aarray<T>The first array.
  • ...$othersarray<U>variadicThe arrays whose values follow, in order.

Return value

Returns array<T|U>. A list renumbered from "0"; every key is discarded.

Examples

Join two lists

<?nvs
// Shows how to join two lists into one. The values of the first list come
// first, then the values of the second.
array<string> $morning = ['Ada', 'Grace'];
array<string> $afternoon = ['Alan', 'Edsger'];
// This prints Ada, Grace, Alan and Edsger, one name per line.
array<string> $everyone = Core\Arr::appendAll($morning, $afternoon);
foreach ($everyone as string $name) {
echo $name, "\n";
}
Output
Ada
Grace
Alan
Edsger

The keys are not kept

<?nvs
// Shows what happens to the keys. The result is a list numbered from 0, so
// every key you gave is replaced by a number.
array<int> $first = ['a' => 1, 'b' => 2];
array<int> $second = ['b' => 3];
// This prints [1,2,3]. Both entries named "b" are kept, because nothing is
// compared here.
array<int> $joined = Core\Arr::appendAll($first, $second);
echo Core\Json::encode($joined), "\n";
Output
[1,2,3]

Collect the rows of every page

<?nvs
// Shows how to collect the rows of several pages into one list, as a program
// does after reading an API one page at a time.
array<array<string>> $pages = [
['order-1001', 'order-1002'],
['order-1003'],
['order-1004', 'order-1005'],
];
array<string> $all = [];
foreach ($pages as array<string> $page) {
$all = Core\Arr::appendAll($all, $page);
}
// This prints 5, and then the five order numbers in the order they were read.
echo Core\Arr::count($all), "\n";
echo Core\Json::encode($all), "\n";
Output
5
["order-1001","order-1002","order-1003","order-1004","order-1005"]