Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 23 / 68

Transforming an Array (array_map)

In this lesson you will learn how to transform an array with array_map so you can apply the same operation to every element at once. This is for anyone searching for "PHP array_map how to use".

array_map(function, array) applies the same operation to every element and produces a new array. Think of it as a machine on a conveyor belt that processes every product that passes through it in the same way. Compared with writing a for loop, what you are trying to do shows up directly in the code.

The sample code builds a new array with every element doubled using array_map(fn($n) => $n * 2, $nums). Arrow functions (fn) let you write an anonymous function even more briefly, a feature of PHP 7.4 and later.

A common stumbling block for beginners is the difference between fn (an arrow function) and function (a regular anonymous function). An arrow function automatically captures variables from the enclosing scope, so you do not need to import them explicitly with use. Knowing that difference lets you write more concise code.

It is a technique you will meet constantly in practice, used every day for reshaping data fetched from a database into a form ready for display.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)