typestar

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

  1. array_map with an fn arrow squares every element into a new array.
  2. array_filter keeps the evens but also their original keys.
  3. array_values renumbers from zero; array_sum and max reduce to one number.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Arrays, step 9 of 27 in Language basics.

← Previous Next →