String and array functions

Intermediate

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 $fn to 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 $fn returns true. The keys stay the same, so the result can have gaps in its indexes. Use array_values if 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, write strlen($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

  1. The line is split into nine words with explode.
  2. ucwords capitalises every word.
  3. array_map('strlen', $words) gives the lengths. array_filter keeps the words longer than three letters.
  4. array_sum and array_reduce both add the lengths. The two results agree.
  5. usort sorts by length first and by text second.
  6. array_unique removes the second the.
  7. array_reverse, array_count_values, array_merge and range work on small lists.
  8. wordwrap breaks the sentence into lines of at most ten characters, and sprintf pads 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_map takes the function first, array_filter takes the array first.
  • Expecting array_filter to renumber the keys. Use array_values for that.
  • Writing a sort function that returns true or false instead of a number; use <=>.
  • Forgetting that usort changes 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

1. Which function applies a function to every item and returns a new array?
2. What should a usort callback return?
3. What does array_filter do with the keys it keeps?
4. Which function turns a string into an array of words?

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.