PHP array_map PHP array map

PHP Array Map (array_map function) With Keys

PHP provides a rich set of built-in functions to manipulate arrays efficiently. One such function is, which allows you to map and apply a callback function to each element of an array and return a new array with the modified values in PHP (even with the key value). PHP array_map uses a callback function (to map an array or arrays even with keys) to send each element of an array or arrays used as arguments for the callback to modify elements. The PHP array_map() is a built-in function in PHP and it helps to modify and map all elements in one array or more arrays according to some user-defined condition and keys.

Returned values can be changed by the callback function. This function can be a PHP built-in function or a custom user-made function.

array_map is a function to modify and map elements of arrays and it is categorized under the PHP array functions.

$arr = array(1, 2, 3, 4);

function double_it($value)
{
    return 2 * $value;
}

var_dump(array_map('double_it', $arr));

This is a simple example of a mapping array in PHP, in the following, we will discuss more about mapping. Let’s dive in.

Read more about PHP Array in our tutorial.

PHP array_map function (PHP array map syntax)

With array_map you could map and modify each element of the given array based on your PHP callback function even by key and value.

This function is available in PHP 4.0.6 and higher.

array_map( callback_func, array1, array2, array3, ...);
callback_funcRequiredThe callback function could be PHP built-in or a custom user-made function. This function runs for each element in each array.
array1RequiredAn array to run through the callback function.
array2OptionalAn array to run through the callback function.
array3OptionalAn array to run through the callback function.
Return ValueReturns an array containing the values of array1, after applying the callback function to each element.

Note that PHP array_map() can accept multiple arrays as arguments. If multiple arrays are provided, the callback function should expect the same number of arguments as the number of arrays passed.

The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.

Let’s assume that you have a list of numbers and you have to double them. You could use a PHP foreach loop and double every element of the array or use the array_map() function. In this tutorial, we are going to talk about array_map in PHP.

Using PHP array_map() with a Callback Function

To use PHP array_map(), you need to define a callback function that will be applied to each element of the array(s). The callback function can be defined in various ways, including anonymous functions, named functions, or even class methods.

1. Using Anonymous Functions

$modifiedArray = array_map(function ($element) {
    // Modify the element as desired
    return $modifiedElement;
}, $originalArray);

2. Using Named Functions

function modifyElement($element) {
    // Modify the element as desired
    return $modifiedElement;
}

$modifiedArray = array_map('modifyElement', $originalArray);

3. Using Class Methods

class ElementModifier {
    public static function modify($element) {
        // Modify the element as desired
        return $modifiedElement;
    }
}

$modifiedArray = array_map(['ElementModifier', 'modify'], $originalArray);

Using PHP array_map on Indexed array

Send each value of a PHP array to a function, and multiply each value by 2 using the map.

$arr = array(1, 2, 3, 4);

function double_it($value)
{
    return 2 * $value;
}

var_dump(array_map('double_it', $arr));

Output

array (size=4)
  0 => int 2
  1 => int 4
  2 => int 6
  3 => int 8

The array_map() function sends each value of an array to the double_it() function and returns an array with new values.

Using array_map function on associative arrays in PHP

The array_map() function does not directly support using the array key as an input. To involve the keys in PHP array_map() function you have to use array_keys() function.

$cars = [
    'Ferrari' => 'Italy',
    'Benz' => 'Germany',
];

function callback_func($key, $value)
{
    return "$key => $value";
}

$result = array_map('callback_func', array_keys($cars), array_values($cars));

var_dump($result);

Output:

array (size=2)
  0 => string 'Ferrari => Italy' (length=16)
  1 => string 'Benz => Germany' (length=15)

Null callback PHP function: Creating an array of arrays using the array_map function

The null value can be passed as a value to the callback function to perform a zip operation on multiple arrays. If only an array is provided, array_map() will return the input array.

$num1 = array(1, 2, 3, 4, 5);
$num2 = array(6, 7, 8, 9, 10);

var_dump(array_map(null, $num1, $num2));

Output:

array (size=5)
  0 => 
    array (size=2)
      0 => int 1
      1 => int 6
  1 => 
    array (size=2)
      0 => int 2
      1 => int 7
  2 => 
    array (size=2)
      0 => int 3
      1 => int 8
  3 => 
    array (size=2)
      0 => int 4
      1 => int 9
  4 => 
    array (size=2)
      0 => int 5
      1 => int 10

The real example for this section could be like this:

You have a list of car drivers’ names and a list of car names and you want to join them together.

$drivers = array('Ben', 'Mark', 'Edi');
$cars = array('Ferrari', 'Benz', 'BMW');

var_dump(array_map(null, $drivers, $cars));

Output:

array (size=3)
  0 => 
    array (size=2)
      0 => string 'Ben' (length=3)
      1 => string 'Ferrari' (length=7)
  1 => 
    array (size=2)
      0 => string 'Mark' (length=4)
      1 => string 'Benz' (length=4)
  2 => 
    array (size=2)
      0 => string 'Edi' (length=3)
      1 => string 'BMW' (length=3)

Read More: PHP Array Merge

Using PHP array_map on an array of objects

In this section, you are going to create a class named User and an array of objects of the User class. This section shows you how to use an array map with a PHP class.

class User
{
    public $username;
    public $password;
    function __construct($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
    }
}

$users = array(
    new User('honar', '123456'),
    new User('systems', '456789')
);

function get_username($user)
{
    return $user->username;
}

$usernames = array_map('get_username', $users);

var_dump($usernames);

Output

array (size=2)
  0 => string 'honar' (length=5)
  1 => string 'systems' (length=7)

In this example, there is a class named User that stores the username and password as strings. There is an array that stores the objects of the users. Function get_username() took one parameter that is an object of the User class and returned its username.

array_map uses get_username function and return $users usernames in array.

PHP array_map() with keys and values

The array_map() function in PHP applies a callback function to each element of an array to map and return a new array with the modified values. By default, it preserves the original keys of the array. However, it is also possible to manipulate the keys using PHP array_map() by passing multiple arrays as arguments, where the first array contains the key and subsequent arrays contain the corresponding value.

PHP built-in array_map() function with keys becomes useful when you want to modify the value of the existing key. You can achieve this by providing an array of keys and a corresponding array of values to array_map() in PHP. The callback function then operates on the values while preserving the keys.

$keys = array('key1', 'key2', 'key3');
$values = array(10, 20, 30);

$modifiedArray = array_map(function ($value) {
    return $value * 2;
}, array_combine($keys, $values));

print_r($modifiedArray);

Output

Array
(
    [key1] => 20
    [key2] => 40
    [key3] => 60
)

In certain cases, you might want to completely change the keys of an array based on some criteria or transformation. PHP array_map() with keys can help you achieve this by applying a callback function that generates the new keys.

$values = array(1, 2, 3, 4, 5);

$newArray = array_map(function ($value) {
    return 'key_' . $value;
}, array_combine(range(1, count($values)), $values));

print_r($newArray);

Output

Array
(
    [key_1] => 1
    [key_2] => 2
    [key_3] => 3
    [key_4] => 4
    [key_5] => 5
)

Conclusion

The array_map() function in PHP provides a convenient way to map and apply a callback function to map each element of an array even with keys. It allows you to modify array elements easily and create a new array with the modified values. Whether you need to perform simple calculations, manipulate strings, or map multiple arrays simultaneously, array_map() can be a powerful tool in your PHP programming arsenal.

Example #1 of PHP array map

Change English numbers to Arabic numbers.

function change($en_number)
{
    $ar_numbers = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
    return $ar_numbers[intval($en_number)];
}

$str = "0 1 2 3 4 5 6 7 8 9";

print_r(array_map('change', explode(' ', $str)));
Array ( [0] => ۰ [1] => ۱ [2] => ۲ [3] => ۳ [4] => ۴ [5] => ۵ [6] => ۶ [7] => ۷ [8] => ۸ [9] => ۹ ) 

In this example exploded $str that length must be equal to $ar_numbers length.

Read More: PHP Explode Functions

Example #2

Lowercase all car names in the array with the PHP array_map function.

$cars = array('Ferrari', 'Benz', 'BMW');

function tolowercase($carName)
{
    return strtolower($carName);
}

var_dump(array_map('tolowercase', $cars));

Output:

array (size=3)
  0 => string 'ferrari' (length=7)
  1 => string 'benz' (length=4)
  2 => string 'bmw' (length=3)

The simple way to do this is using the PHP strtolower function directly.

$cars = array('Ferrari', 'Benz', 'BMW');

var_dump(array_map('strtolower', $cars));

Output

array (size=3)
  0 => string 'ferrari' (length=7)
  1 => string 'benz' (length=4)
  2 => string 'bmw' (length=3)

Example #3

Doubling the Elements of an Array

$numbers = [1, 2, 3, 4, 5];

$doubledNumbers = array_map(function ($number) {
    return $number * 2;
}, $numbers);

Output

[2, 4, 6, 8, 10]

Example #4

Applying Capitalization to an Array of Names

$names = ['john doe', 'jane smith', 'jake jackson'];

$capitalizedNames = array_map('ucwords', $names);

Output

['John Doe', 'Jane Smith', 'Jake Jackson']

Example #5

Mapping Multiple Arrays

$numbers1 = [1, 2, 3];
$numbers2 = [4, 5, 6];

$sums = array_map(function ($num1, $num2) {
    return $num1 + $num2;
}, $numbers1, $numbers2);

Output

[5, 7, 9]

You may like

Shopping Cart