Wikis & learning

Transform a list with a callback

A callback lets an array operation ask your function to process each element. Keep the callback focused on one value and return a result instead of printing inside it.

A callback lets an array operation ask your function to process each element. Keep the callback focused on one value and return a result instead of printing inside it.

Walkthrough

array_map returns a new list. The arrow function expresses a single transformation; the original list still contains the raw fields. A later step chooses how to display the transformed data.

PHP example

<?php
$raw = ['  Pine  ', ' ash ', ' OAK'];
$clean = array_map(fn(string $v): string => strtolower(trim($v)), $raw);
echo implode(' | ', $clean);

Expected output

pine | ash | oak

Change and check

Trim the same input with a named function instead of an arrow function. Verify that both transformations preserve the number of items.