Core\Arr::map
Core\Arr::map(array<T> $a, callable(T, string): U $fn): array<U>Core\Arr::map( array<T> $a, callable(T, string): U $fn, ): array<U>
Makes a new array by replacing every value with what a function returns for it.
You give Core\Arr::map an array and a function. The function receives the value and the key, and returns the new value. A function that needs only the value declares only that one parameter.
The keys stay as they are, and the result has exactly as many entries as the array you gave. The type of the result follows the function: a function returning string over an array<int> gives you an array<string>.
The function runs once for each value, in order. If it throws an error, map stops and throws the same error.
Good to know: to change the keys instead of the values, use Core\Arr::mapKeys. To leave entries out, use Core\Arr::filter. To combine all values into one, use Core\Arr::reduce.
Parameters
$aarray<T>The array to map.$fncallable(T, string): UCalled as($value, $key)per entry, and may declare fewer parameters; its return type is the result'sU.
Return value
Returns array<U>. One entry per entry of $a, under the same key. Its value is the callback's result. For an array<E, T>, the result is an array<E, U>.
Examples
Transform values
<?nvs// Shows how to replace every value in an array. `Core\Arr::map` calls the// function once per entry and collects what it returns.
var $squares = Core\Arr::map([1, 2, 3, 4], fn(int $n): int => $n * $n);
// This prints 1, 4, 9 and 16, one per line.foreach ($squares as int $v) { echo $v, "\n";}14916Keys are preserved
<?nvs// Shows a function that reads the key as well as the value. `Core\Arr::map`// gives it both, and the result keeps every key of the array it came from.
array<int> $prices = ['coffee' => 350, 'cake' => 420];
var $labels = Core\Arr::map($prices, fn(int $cents, string $item): string => $item . ': ' . Core\Str::format('%.2f', $cents / 100.0));
// This prints `coffee: 3.50` and `cake: 4.20`.foreach ($labels as string $line) { echo $line, "\n";}coffee: 3.50cake: 4.20Clean up what a form sent
<?nvs// Removes the spaces around every field a form sent. A program does this before// it saves the values or compares them with something else.
array<string> $form = ['name' => ' Ida Weber ', 'city' => 'Bonn '];array<string> $clean = Core\Arr::map($form, fn(string $value) => Core\Str::trim($value));
// This prints `name: [Ida Weber]` and `city: [Bonn]`.foreach ($clean as string $field => string $value) { echo $field, ': [', $value, ']', "\n";}name: [Ida Weber]city: [Bonn]