Lesson 17 of 100
Arrays12 min5 checksPHP 8.5

Transforming arrays with array_map and array_filter

Learn to transform every value with array_map, keep only matching values with array_filter, and handle the keys each function preserves.

01 · THE IDEAREAD → TRY → LEARN

Why transform arrays?

Much PHP code takes a list of values and produces a new list. You might double prices, trim user input or drop empty entries. You could write a foreach loop each time, but two built-in functions describe the intent directly:

  • array_map() produces one output value for every input value.
  • array_filter() keeps only the input values that pass a test.

Neither function changes the array you pass in. Each returns a new array.

Mapping with array_map

The PHP 8.4 signature is:

array_map(?callable $callback, array $array, array ...$arrays): array

The callback receives one element and returns its replacement. An arrow function is a compact way to write one:

Example
<?php
$numbers = [1, 2, 3];
$doubled = array_map(fn(int $n): int => $n * 2, $numbers);
echo json_encode($doubled), "\n";
Output
[2,4,6]

The result has the same number of elements as the input. When you pass exactly one array, array_map() preserves its keys, so string keys stay attached to their transformed values. When you pass several arrays, the callback receives one element from each, and the result gets fresh sequential integer keys. The callback must accept as many parameters as the number of arrays you pass.

Passing null as the callback is a special case. With several arrays it zips them into rows. With a single array it returns that array unchanged.

Filtering with array_filter

array_filter() calls your callback for each value. If the callback returns a truthy result, the element stays in the output. Here is the important detail: the surviving elements keep their original keys. After removing items from a list, the remaining keys can have gaps.

Example
<?php
$numbers = [1, 2, 3, 4, 5, 6];
$even = array_filter($numbers, fn(int $n): bool => $n % 2 === 0);
echo json_encode($even), "\n";
echo json_encode(array_values($even)), "\n";
Output
{"1":2,"3":4,"5":6}
[2,4,6]

The first line prints a JSON object because the keys are 1, 3 and 5. A JSON list needs keys 0, 1, 2 and so on. Wrapping the result in array_values() renumbers the elements, giving the list [2,4,6].

If you call array_filter() without a callback, it removes every falsy value, including 0, '0', '', false, null and empty arrays. This is convenient, but be sure that discarding 0 is what you want.

Combining both steps

Real transformations are often a small pipeline. Clean each value first, then remove what is now useless, then renumber if you need a list.

Example
<?php
$words = ['  php ', '', ' arrays', '  '];
$trimmed = array_map('trim', $words);
$nonEmpty = array_filter($trimmed, fn(string $word): bool => $word !== '');
echo json_encode($nonEmpty), "\n";
echo json_encode(array_values($nonEmpty)), "\n";
Output
{"0":"php","2":"arrays"}
["php","arrays"]

The whitespace-only strings become empty after trim, so the filter removes them. The first output shows keys 0 and 2, which are leftovers from the original positions. The second output is a clean list.

The order of the steps matters. If you filter first, the callback of array_map() runs on fewer elements. If you map first, the filter can test the cleaned values.

Common mistakes

  • Expecting array_filter() to renumber keys. It does not. Use array_values() when you need a list.
  • Forgetting that array_map() returns one output element per input element. It cannot remove elements, so use array_filter() for that.
  • Passing a callback with the wrong number of parameters for the arrays you supply.
  • Using array_filter() with no callback when 0 or '0' are valid data.

Exercise contract

Write positive_squares(array $numbers): array. It receives a list of integers and returns a new list containing the square of each number that is strictly greater than zero. Keep the original order. The result must be a list with keys 0, 1, 2 and so on, even when some inputs are removed. Zero and negative numbers are dropped. If nothing qualifies, return an empty array.

Recap

array_map() transforms values one-to-one, and array_filter() selects values while keeping their keys. Combine them for pipelines, and finish with array_values() when the result must be a list.

Before you start

Arrays · Functions

You’ll practice
  • Transform each value with array_map
  • Filter values while understanding preserved keys
Your task

Make positive_squares() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.