Introduction
PHP comes with a huge library of built-in functions, and an experienced PHP programmer writes fewer loops than a beginner because they know which function already does the job. In this lesson you combine the string functions and the array functions into short, powerful pipelines: split a sentence into words, change every word, keep only some, sort and join them again. The key idea is to pass a small function, usually an arrow function, to a built-in function.
How it works
Four functions take another function as an argument, and together they replace most loops:
array_map($fn, $array)applies$fnto every item and returns the new array. For example,array_map('strlen', $words)gives the length of every word.array_filter($array, $fn)keeps only the items for which$fnreturns true. The keys stay the same, so the result can have gaps in its indexes. Usearray_valuesif you need a fresh list.array_reduce($array, $fn, $start)combines all items into one value. The function receives the result so far, called$carry, and the next item.usort($array, $fn)sorts with your own rule. The function compares two items and returns a negative number, zero or a positive number. The spaceship operator<=>is made for this. To sort by two rules, writestrlen($a) <=> strlen($b) ?: strcmp($a, $b): if the lengths are equal, the short?:falls back to the text comparison.
Other helpful array functions are array_unique (remove repeats), array_reverse, array_merge (join arrays), array_count_values (count how often each value appears), array_keys, array_combine, array_slice, array_sum, array_product and range(1, 5), which creates a list of numbers.
For strings: explode($separator, $text) splits into an array and implode($glue, $array) joins back. str_split cuts a text into letters, wordwrap($text, $width, "\n", true) breaks long text into lines, and ucwords capitalises each word. sprintf builds a string with a format, just like printf, but returns it instead of printing. In a format, %05.1f means a number with one decimal, padded with zeros to width 5, %-6s pads text on the right and %6s pads on the left. The function number_format($x, 2) writes a number with two decimals and thousands separators.
When you chain these functions, read the code from the inside out. In implode(" ", array_map('ucfirst', explode(" ", $line))), the line is first split, then every word is changed, and finally the words are joined.
Example
<?php
$line = trim(fgets(STDIN));
$words = explode(" ", $line);
echo count($words), " words\n";
echo ucwords($line), "\n";
$lengths = array_map('strlen', $words);
echo implode(",", $lengths), "\n";
$long = array_filter($words, fn($w) => strlen($w) > 3);
echo implode(" ", $long), "\n";
echo array_sum($lengths), "\n";
$total = array_reduce($words, fn($carry, $w) => $carry + strlen($w), 0);
echo $total, "\n";
usort($words, fn($a, $b) => strlen($a) <=> strlen($b) ?: strcmp($a, $b));
echo implode(" ", $words), "\n";
echo implode(" ", array_unique(explode(" ", $line))), "\n";
echo implode(",", array_reverse([1, 2, 3])), "\n";
print_r(array_count_values(str_split("hello")));
echo implode(",", array_merge([1, 2], [3, 4])), "\n";
echo implode(",", range(1, 5)), "\n";
echo wordwrap("A very long sentence here", 10, "\n", true), "\n";
echo sprintf("%05.1f|%-6s|%6s", 3.14159, "ab", "cd"), "\n";Input used: the quick brown fox jumps over the lazy dog
Line by line
- The line is split into nine words with
explode. ucwordscapitalises every word.array_map('strlen', $words)gives the lengths.array_filterkeeps the words longer than three letters.array_sumandarray_reduceboth add the lengths. The two results agree.usortsorts by length first and by text second.array_uniqueremoves the secondthe.array_reverse,array_count_values,array_mergeandrangework on small lists.wordwrapbreaks the sentence into lines of at most ten characters, andsprintfpads and formats values.
Expected result
With the input the quick brown fox jumps over the lazy dog, it prints:
9 words
The Quick Brown Fox Jumps Over The Lazy Dog
3,5,5,3,5,4,3,4,3
quick brown jumps over lazy
35
35
dog fox the the lazy over brown jumps quick
the quick brown fox jumps over lazy dog
3,2,1
Array
(
[h] => 1
[e] => 1
[l] => 2
[o] => 1
)
1,2,3,4
1,2,3,4,5
A very
long
sentence
here
003.1|ab | cd
In the real world
Data processing is mostly map, filter, sort and reduce: take the orders, keep the ones of one customer, sort by date and add up the prices. Learning to express a job in these steps makes code shorter and closer to the way you describe the problem. The same ideas exist in JavaScript, Python and Java streams.
Common mistakes
- Mixing the argument order.
array_maptakes the function first,array_filtertakes the array first. - Expecting
array_filterto renumber the keys. Usearray_valuesfor that. - Writing a sort function that returns true or false instead of a number; use
<=>. - Forgetting that
usortchanges the array and returns only true.
Best practices
- Use a built-in function before writing your own loop.
- Use arrow functions for short callbacks.
- Chain steps in the order split, change, filter, sort, join.
- Keep each step easy to read; use a variable for long chains.
Summary
array_map, array_filter, array_reduce and usort take a function and replace many loops. explode, implode, str_split, wordwrap, sprintf and number_format handle text. Use <=> for sorting rules, and array_values to renumber after filtering.
Quick check
Key takeaways
- array_map, array_filter, array_reduce and usort take a function and replace loops.
- explode, implode, wordwrap and sprintf handle text.
- Use the spaceship operator for sorting rules.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.