PHP array_map() Function Tutorial

beginner
8 min

PHP array_map() Function Tutorial

Welcome to your PHP array_map() Function journey! 🎯 In this lesson, you'll learn how to use the powerful array_map() function in PHP. By the end of this tutorial, you'll be able to manipulate arrays with confidence, just like a seasoned developer.

What is the array_map() function?

The array_map() function is a built-in PHP function that applies a user-defined function to each element of an array. It creates a new array with the results. πŸ’‘ Pro Tip: This function is particularly useful when you want to perform the same operation on multiple array elements.

Basic usage of array_map()

Let's dive in with a simple example. Suppose we have an array of numbers, and we want to square each number.

php
<?php $numbers = [1, 2, 3, 4, 5]; $squaredNumbers = array_map(function($number) { return $number * $number; }, $numbers); print_r($squaredNumbers); ?>

In this example, we've defined an array $numbers containing some numbers. We've also created an anonymous function that squares a number. Using array_map(), we apply this function to each number in the array and store the results in $squaredNumbers.

array_map() with callback functions

Instead of using an anonymous function, you can also use an existing function as the callback for array_map().

php
<?php function square($number) { return $number * $number; } $numbers = [1, 2, 3, 4, 5]; $squaredNumbers = array_map('square', $numbers); print_r($squaredNumbers); ?>

In this example, we've defined a square() function that squares a number. We then use this function as the callback for array_map() to get the squared numbers.

array_map() with associative arrays

array_map() can also be used with associative arrays. The key-value pairs of the input array will be passed as an associative array to the callback function.

php
<?php $users = [ ['name' => 'John', 'age' => 25], ['name' => 'Jane', 'age' => 22], ['name' => 'Mike', 'age' => 30] ]; function addAge($user) { return [ 'name' => $user['name'], 'age' => $user['age'] + 10 ]; } $usersWithTenMoreYears = array_map('addAge', $users); print_r($usersWithTenMoreYears); ?>

In this example, we have an associative array $users containing user data. We've also defined a addAge() function that adds 10 years to the age of a user. Using array_map(), we apply this function to each user in the array and store the results in $usersWithTenMoreYears.

Quiz

Quick Quiz
Question 1 of 1

Given an array `$names` containing strings, write a function `capitalizeNames()` that creates a new array with the first letter of each name capitalized. What would be the function definition for `capitalizeNames()`?

Happy coding, and remember: with PHP's array_map() function, the possibilities are endless! πŸŽ‰