Array functions in PHP
map, filter, and sum: transforming arrays without writing a loop.
<?php
$nums = [3, 1, 4, 1, 5, 9, 2, 6];
$squares = array_map(fn($n) => $n * $n, $nums);
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
echo implode(" ", $squares), PHP_EOL;
// array_filter keeps original keys; array_values renumbers them
print_r(array_values($evens));
echo array_sum($nums), " total, ", max($nums), " max", PHP_EOL;
How it works
array_mapwith anfnarrow squares every element into a new array.array_filterkeeps the evens but also their original keys.array_valuesrenumbers from zero;array_sumandmaxreduce to one number.
Keywords and builtins used here
array_filterarray_maparray_sumarray_valuesechoimplodemaxprint_r
The run, in numbers
- Lines
- 10
- Characters to type
- 341
- Tokens
- 88
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 70 seconds.
Step 3 of 3 in Arrays, step 9 of 27 in Language basics.