Skip to content

Core\Arr

Works with arrays. It finds, sorts, changes and combines elements. Every method returns a new array, and the array you pass in does not change.

Core\Arr has the array functions as static methods. Each one returns a new array and never changes its argument. Core\Arr::sort returns the sorted array, and append returns the longer one. Keys are always string: $a[0] and $a["0"] are the same entry, keys returns array<string>, and a callback's key parameter is string. A callback receives ($value, $key) and may declare fewer parameters. reduce passes the carry first. A missing value is null: first, last, find, keyOf and min return null for an empty array. count returns a uint. $a + $b does not compile. overlay and underlay combine maps, and appendAll joins lists.

shapeAs<T> is the one member that answers something other than an array. It reads its subject as the type written at the call site — an inline shape, { name: string, score: int }, or a class carrying #[Core\Json\Derive] — converting every named field with as and leaving every key the type does not name behind, so a form carrying a CSRF token does not break a handler reading two fields out of it. That is the whole story for loose input: an array<T> is homogeneous and there is no per-key-typed one, so a form, a query string or a decoded document is converted once, at the boundary, where a failure is still a 400 — and nothing downstream is left holding a mixed to check. A field that is absent, or that holds a value as refuses for its declared type, throws ParseError carrying every field that failed at its own dotted path, rather than the first of them. { name?: T } marks a key that may be absent, and ?? and isset read one without throwing. Core\Request::queryParametersAs and formFieldsAs are this member over what a request carried. Text that came from outside the program, such as a form or an array<mixed>, is tainted. A text field it fills must then be declared tainted too.

<?nvs
array<int> $scores = ['ada' => 92, 'bo' => 67, 'cy' => 85, 'di' => 74];
var $passed = Core\Arr::filter($scores, fn(int $n): bool => $n >= 70);
echo Core\Json::encode($passed), "\n";
var $ranked = Core\Arr::sort($passed, { order: Core\Arr::Order::Desc, preserveKeys: true });
echo Core\Json::encode(Core\Arr::keys($ranked)), "\n";
echo Core\Arr::first($ranked) ?? 0, ' ', Core\Arr::firstKey($ranked) ?? '-', "\n";
var $labels = Core\Arr::map($scores, fn(int $n, string $k): string => $k . ':' . ($n as string));
echo Core\Str::join(Core\Arr::values($labels), ' '), "\n";
echo Core\Arr::sum($scores), ' ', Core\Arr::count($scores), ' ', Core\Arr::average($scores) ?? 0, "\n";
int $total = Core\Arr::reduce($scores, fn(int $carry, int $n): int => $carry + $n, 0);
echo $total, ' ', Core\Arr::max($scores) ?? 0, "\n";
array<int> $evens = Core\Arr::filter(Core\Arr::range(1, 10), fn(int $n): bool => $n % 2 == 0);
echo Core\Json::encode(Core\Arr::values($evens)), ' ', Core\Arr::contains($evens, 4) ? 'yes' : 'no', "\n";
var $byLength = Core\Arr::groupBy(['fig', 'pear', 'kiwi', 'plum'], fn(string $w): int => Core\Str::length($w) as int);
echo Core\Json::encode($byLength), "\n";
echo Core\Json::encode($scores), "\n";
var $entry = Core\Arr::shapeAs<{ name: string, score: int, note?: string }>(['name' => 'ada', 'score' => '92', 'csrf' => 't0ken']);
echo $entry->name, ' ', $entry->score as string, ' ', $entry->note ?? 'no note', "\n";
Output
{"ada":92,"cy":85,"di":74}
["ada","cy","di"]
92 ada
ada:92 bo:67 cy:85 di:74
318 4 79.5
318 92
[2,4,6,8,10] yes
{"3":["fig"],"4":{"1":"pear","2":"kiwi","3":"plum"}}
{"ada":92,"bo":67,"cy":85,"di":74}
ada 92 no note

Members

57 members.

MemberSignature
countcount(array<T> $a): uint
filterfilter(array<T> $a, callable(T, string): bool $predicate): array<T>
mapmap(array<T> $a, callable(T, string): U $fn): array<U>
mapKeysmapKeys(array<T> $a, callable(T, string): int|uint|string $fn): array<T>
groupBygroupBy(array<T> $a, callable(T, string): int|uint|string $key): array<array<T>>
reducereduce(array<T> $a, callable(U, T, string): U $fn, U $initial): U
findfind(array<T> $a, callable(T, string): bool $predicate): ?T
findKeyfindKey(array<T> $a, callable(T, string): bool $predicate): ?string
anyany(array<T> $a, callable(T, string): bool $predicate): bool
allall(array<T> $a, callable(T, string): bool $predicate): bool
isEmptyisEmpty(array<T> $a): bool
hasKeyhasKey(array<T> $a, int|uint|string $key): bool
containscontains(array<T> $haystack, T $needle): bool
keyOfkeyOf(array<T> $haystack, T $needle): ?string
isListisList(array<T> $a): bool
keyskeys(array<T> $a): array<string>
valuesvalues(array<T> $a): array<T>
firstfirst(array<T> $a): ?T
lastlast(array<T> $a): ?T
firstKeyfirstKey(array<T> $a): ?string
lastKeylastKey(array<T> $a): ?string
sliceslice(array<T> $a, int $offset, ?int $length = null, { preserveKeys?: bool }): array<T>
replaceRangereplaceRange(array<T> $a, int $offset, ?int $length, array<T> $replacement = []): array<T>
chunkchunk(array<T> $a, uint $size, { preserveKeys?: bool }): array<array<T>>
appendappend(array<T> $a, T ...$values): array<T>
prependprepend(array<T> $a, T ...$values): array<T>
withoutFirstwithoutFirst(array<T> $a): array<T>
withoutLastwithoutLast(array<T> $a): array<T>
withoutNullwithoutNull(array<?T> $a): array<T>
padStartpadStart(array<T> $a, uint $size, T $value): array<T>
padEndpadEnd(array<T> $a, uint $size, T $value): array<T>
reversereverse(array<T> $a, { preserveKeys?: bool }): array<T>
flipflip(array<int|uint|string> $a): array<string>
flattenflatten(array<array<T>> $a): array<T>
flattenDeepflattenDeep(array<mixed> $a): array<mixed>
columncolumn(array<array<T>> $a, int|uint|string $column, { indexBy?: int|uint|string }): array<T>
sortsort(array<T> $a, { by?: callable, order?: Core\Arr::Order, comparator?: callable, preserveKeys?: bool }): array<T>
sortByKeysortByKey(array<T> $a, { order?: Core\Arr::Order, comparator?: callable, keys?: array<int|uint|string> }): array<T>
fillfill(uint $count, T $value): array<T>
fillKeysfillKeys(array<int|uint|string> $keys, T $value): array<T>
rangerange(int $start, int $end, { step?: int }): array<int>
fromKeysAndValuesfromKeysAndValues(array<int|uint|string> $keys, array<T> $values): array<T>
fromfrom(array<T>|Iterable<T>|Iterator<T> $items, { limit?: uint }): array<T>
overlayoverlay(array<T> $base, array<U> ...$layers): array<T|U>
overlayDeepoverlayDeep(array<T> $base, array<U> ...$layers): array<T|U>
underlayunderlay(array<T> $base, array<U> ...$layers): array<T|U>
appendAllappendAll(array<T> $a, array<U> ...$others): array<T|U>
differencedifference(array<T> $a, array<T> $b, { on?: Core\Arr::SetOn, by?: callable, comparator?: callable }): array<T>
intersectionintersection(array<T> $a, array<T> $b, { on?: Core\Arr::SetOn, by?: callable, comparator?: callable }): array<T>
groupCountsgroupCounts(array<T> $a, { by?: callable }): array<uint>
uniqueunique(array<T> $a, { by?: callable }): array<T>
minmin(array<T> $a): ?T
maxmax(array<T> $a): ?T
sumsum(array<int|float|decimal> $a): int|float|decimal
productproduct(array<int|float|decimal> $a): int|float|decimal
averageaverage(array<int|float|decimal> $a): ?float|decimal
shapeAsshapeAs<T>(array<mixed> $a): T

Enums

  • OrderThe direction Core\Arr::sort and sortByKey put elements in. It is the { order: … } option, and it is Asc when you leave it out.
  • SetOnWhich part of an entry Core\Arr::difference and intersection compare. It is the { on: … } option, and it is Values when you leave it out. by and comparator apply to the part it selects.