Working with Strings and Arrays Together
PHP has no list-comprehension syntax the way Python does, or enumerable chaining the way Ruby does — idiomatic PHP reaches for array_filter() (keep only the elements matching a condition) and array_map() (transform every element) instead, usually with a short arrow function as the callback. Combined with explode() (split a string into an array) and implode() (join an array back into a string), these four functions cover most of the everyday string-and-array processing PHP code actually does.
<?php
$words = ["apple", "kiwi", "banana", "fig", "watermelon"];
$longWords = array_filter($words, fn($w) => strlen($w) > 4);
$upper = array_map(fn($w) => strtoupper($w), $longWords);
echo implode(", ", $upper), "\n";
$sentence = "the quick brown fox jumps";
$cap = array_map(fn($w) => ucfirst($w), explode(" ", $sentence));
echo implode(" ", $cap), "\n";
APPLE, BANANA, WATERMELON The Quick Brown Fox Jumps
array_filter($words, fn($w) => strlen($w) > 4) kept only "apple", "banana", and "watermelon" (lengths 5, 6, 10 — all over 4); array_map() then uppercased whatever survived the filter, and implode(", ", ...) joined the results into one readable line. The second example splits a sentence into words with explode(" ", ...), capitalizes each one with ucfirst() via array_map(), and rejoins them with implode(" ", ...) — filter, map, split, and join composing together, the same way a Python comprehension or a Ruby .select.map chain would. Next, and last: error handling — try/catch/throw, and a closing look back at what makes PHP PHP.
Practice exercise
Given $words = ["go", "java", "rust", "c"], filter to words longer than 2 characters, uppercase what remains, and echo the results joined with ", ".