Skip to main content

Transforming a Collection

A transformation takes a collection, such as an array, and builds a new collection from it. The original is not changed.

PHP arrays come with a large family of ready-made functions for this: array_map applies a function to every element, array_merge joins arrays, array_combine glues keys to values, array_column picks one position out of every row, and implode turns an array into text. Where no ready-made function fits, a short foreach loop does the job.

The same PHP array works as a list and as a key:value store. A plain list has the keys 0, 1, 2 and so on; an associative array has keys you choose. Both keep their entries in insertion order, and both are used on this page.


Map

The map operation applies the same function to every element and collects the answers in a new array of the same length. For example, it can turn 1, 2, 3 into 3, 6, 9.

In PHP this is exactly what array_map does: it takes the function first and the array second, and returns a new array. The function is often a short arrow function like fn($x) => $x * 3.

array_map never changes the original array. It builds and returns a new one, so you can keep both.

Map with array_map

array_map calls the arrow function on every element and returns a new array. Here it multiplies each number by 3, and implode prints the new array as 3, 6, 9.

Prompt
Use array_map with an arrow function to multiply each number in the array 1, 2, 3 by 3. Print the new array with implode.
Output: PHP script
Map with array_map

Map with the index

Sometimes the position of an element matters too. foreach gives you both the key and the value, and in a plain list the keys are the positions 0, 1, 2. Here each value is multiplied by its own index, so the program prints 0, 2, 6.

Prompt
Loop over the array 1, 2, 3 with foreach, using both the key and the value. Build a new array where each element is value * index, then print it with implode.
Output: PHP script
Map with the index

Skip some results

Sometimes some results should be dropped. Return null for them, then remove the null values with array_filter. Watch out: array_filter keeps the original keys, so the filtered array still has the keys 0 and 2 and json_encode prints it as {"0":3,"2":9}. array_values reindexes it into a clean list: [3,9].

Prompt
Map the array 1, 2, 3 so that 2 becomes null and the other numbers are multiplied by 3. Remove the null with array_filter and print the filtered array with json_encode to show that the original keys are kept, then reindex it with array_values and print it again.
Output: PHP script
Skip some results

Transform array keys

To change the keys of an associative array, transform the keys and glue them back to the values. array_keys gives all keys, array_map('strtoupper', ...) makes them uppercase, and array_combine pairs the new keys with the old values.

Prompt
Start with an associative array from "key1" to 1 and "key2" to 2. Build a new array with the same values but every key changed to uppercase, using array_keys, array_map and array_combine. Print the new array with json_encode.
Output: PHP script
Transform array keys

Transform array values

To change the values, keep the keys and compute new values. array_map can walk two arrays at once — here the keys and the values — so each new value is the old value plus the length of its key: 1 + strlen("key1") is 5.

Prompt
Start with an associative array from "key1" to 1 and "key2" to 2. Build a new array with the same keys where each value is the old value plus the length of its key. Print the new array with json_encode.
Output: PHP script
Transform array values

Zip

Zipping takes two arrays and pairs up their elements by position: the first with the first, the second with the second, and so on.

PHP has a classic idiom for this: array_map(null, $a, $b). When the callback is null and there are several arrays, array_map builds an array of pairs. Note that it does not stop at the shorter array — the missing places are filled with null — so zip arrays of the same length, or cut the longer one with array_slice first.

Zip two arrays

With null as the callback, array_map pairs the two arrays into an array of two-element arrays. json_encode shows the whole result in one line.

Prompt
Combine the arrays red, brown, grey and fox, bear, wolf element by element into an array of pairs using array_map with null as the callback. Print the pairs with json_encode.
Output: PHP script
Zip two arrays

Zip with a transformation

You do not always need the pairs themselves. Give array_map a real callback and both arrays, and it calls the function with one element from each. ucfirst makes the first letter of the animal name uppercase.

Prompt
Combine the arrays red, brown, grey and fox, bear, wolf element by element with array_map. For each pair build a sentence like "The Fox is red", with the first letter of the animal in uppercase, and print one sentence per line.
Output: PHP script
Zip with a transformation

Unzip an array of pairs

Unzipping is the reverse: one array of pairs becomes two arrays. array_column collects the element at one position from every pair — position 0 gives the words and position 1 gives the numbers.

Prompt
Start with an array of pairs: one with 1, two with 2, three with 3. Split it into an array of words and an array of numbers using array_column and print each array on its own line with implode.
Output: PHP script
Unzip an array of pairs

Associate

Associating builds an associative array from a list. Each element gives you one key and one value. An array cannot hold the same key twice, so if two elements produce the same key, the later one wins.

The pattern is a plain foreach loop: start with an empty array and assign $result[$key] = $value for each element. PHP keeps the entries in the order they were added.

Elements as keys

The element itself becomes the key, and a value is computed from it. Here the words are keys and their lengths are values, so the program prints {"one":3,"two":3,"three":5}.

Prompt
Build an associative array from the words one, two, three where each word is a key and its length is the value. Print the array with json_encode.
Output: PHP script
Elements as keys

Elements as values

The element becomes the value, and the key is computed from it. Here the key is the uppercase first letter, taken with $word[0] and strtoupper. Both two and three start with T, so three replaces two and the array has only two entries.

Prompt
Build an associative array from the words one, two, three where the key is the uppercase first letter of the word and the value is the word itself. Print the array with json_encode and notice that "three" replaces "two" under the key T.
Output: PHP script
Elements as values

Compute both key and value

You can compute both the key and the value from the element. Here the key is the first letter and the value is the word length. Again the later T entry wins.

Prompt
Build an associative array from the words one, two, three where the key is the uppercase first letter and the value is the length of the word. Print the array with json_encode.
Output: PHP script
Compute both key and value

Key and value from one element

Sometimes one element carries both parts. explode splits a full name on the space into an array of words, and the list assignment [$first, $last] = ... unpacks it. The last name becomes the key and the first name becomes the value.

Prompt
Start with the full names "Alice Adams" and "Brian Brown". Split each name into words with explode and build an associative array from last name to first name. Print the array with json_encode.
Output: PHP script
Key and value from one element

Flatten

Flattening turns a nested collection, such as an array of arrays, into one plain array with all the elements in order.

In PHP, array_merge joins any number of arrays, and the three dots spread the inner arrays into the call: array_merge(...$nested).

Flatten an array of arrays

The three dots turn array_merge(...$numberSets) into array_merge([1, 2, 3], [4, 5, 6]). Two inner arrays of three numbers become one array of six.

Prompt
Start with an array of arrays: 1, 2, 3 and 4, 5, 6. Flatten it into one array using array_merge with the ... operator, then print it with implode.
Output: PHP script
Flatten an array of arrays

Flatten values from objects

A flat map first takes an array out of every element, then joins all those arrays together. array_map reads the $values property of each container, and array_merge with the three dots glues the three arrays into one.

Prompt
Define a Container class with an array property called values. Make three containers holding one, two, three; four, five; and six, seven, eight. Collect all their values into one array with array_map and array_merge and print it with implode.
Output: PHP script
Flatten values from objects

String Representation

Often you want to show a collection as readable text, for example with commas between the elements.

In PHP, implode takes a separator and an array and returns one string. Numbers are turned into text automatically. The extras — a prefix, a postfix, a limit, or a transformation — are done with string concatenation, array_slice or array_map before joining.

Join with a separator

implode puts ", " between the words and returns one string.

Prompt
Join the words one, two, three into one string with ", " between them using implode. Print the string.
Output: PHP script
Join with a separator

Add a prefix and a postfix

A prefix and a postfix are just text around the joined result. In PHP you add them with the . operator.

Prompt
Join the words one, two, three with " | " between them, add the prefix "start: " and the postfix ": end", and print the result.
Output: PHP script
Add a prefix and a postfix

Limit the number of elements

For a long array you may want to show only the first few elements. range(1, 100) builds the numbers, array_slice($numbers, 0, 10) takes the first 10, and "...>" is added at the end to show that more elements were cut off. implode turns the numbers into text by itself.

Prompt
Make an array with the numbers from 1 to 100 using range. Join only the first 10 of them with ", ", taken with array_slice, and add "<...>" at the end to show the list was cut. Print the result.
Output: PHP script
Limit the number of elements

Transform each element before joining

To change every element before joining, transform the array with array_map first, then implode the result. Here each word becomes "Element: " plus the word in uppercase.

Prompt
Turn each of the words one, two, three into "Element: " followed by the word in uppercase using array_map. Join the results with ", " and print the string.
Output: PHP script
Transform each element before joining