PHP array_map() Function

Topics Covered

Overview

The array_map function in PHP is a powerful tool for transforming arrays. It takes two parameters: a callback function and an array. The callback function is applied to each array element, and the results are returned in a new array. This function enables easy manipulation and modification of array data without complex loops. It is particularly useful when you need to apply the same operation to multiple elements of an array, such as performing calculations, applying string transformations, or extracting specific values. With array_map,` PHP developers can efficiently transform array data with minimal code.

Introduction to array_map in php

The array_map function in PHP is a powerful and versatile tool that allows developers to transform and manipulate arrays with ease. It provides a concise and efficient way to apply a callback function to every element of an array, producing a new array with the transformed values. This function eliminates the need for explicit loops and reduces code complexity.

The syntax of array_map is straightforward. It takes two parameters: a callback function and an array. The callback function defines the operation that will be applied to each element of the array. It can be an anonymous function or a named function. The array parameter represents the input array that will transform.

Syntax of array_map in php

The syntax of the array_map function in PHP is as follows:

Run the above code in your editor for a better and clear explanation.

Parameter Values of array_map in php

  • $callback (callable): The callback function is to be applied to each element of the input arrays.
  • $array1 (array): The first array to be processed.
  • $arrays (array, optional): Additional arrays to be processed. You can specify multiple arrays separated by commas.

Return Value of array_map in php

  • The array_map function returns an array containing the results of applying the callback function to the corresponding elements of the input arrays. The resulting array will have the same length as the input arrays.

Changelog

The changelog of array_map in PHP includes the following points which are written below:

  • PHP 4.0.6: The array_map function was introduced in PHP 4.0.6.
  • PHP 4.3.0: The array_map function started supporting multiple arrays as input. Previously, it only accepted a single array.
  • PHP 5.3.0: The array_map function gained support for anonymous functions as the callback.
  • PHP 7.1.0: The array_map function was optimized for performance, resulting in improved efficiency and reduced memory consumption.
  • PHP 7.2.0: Nullable types were added to the array_map function's signature, allowing nullable callable types and array types.
  • PHP 8.0.0: The array_map function's behavior was changed to preserve keys by default. Previously, it would reset the keys in the resulting array.
  • PHP 8.0.0: The array_map function introduced support for named parameters, allowing developers to pass arguments by name instead of position.

Php Version

The array_map() function in PHP allows you to apply a callback function to each element of an array and create a new array with the results. Here is a detailed changelog for array_map() in PHP, highlighting important changes and additions over different PHP versions:

PHP 4.0.6:

  • Initial release of the array_map() function.

PHP 5.0.0:

  • The callback function is no longer limited to being a string representing a global function name. It can now be any valid PHP callable, including anonymous functions and object methods.

PHP 5.1.0:

  • The callback function is now allowed to accept additional arguments after the array elements. This means you can pass extra arguments to the callback function when using array_map().

PHP 5.3.0:

  • The ability to use $this as a callback for object methods was added. This allows using array_map() with methods of the current object.

PHP 5.4.0:

  • The array_map() function became variadic, meaning it can accept multiple arrays as input. Previously, it only worked with a single array.

PHP 7.1.0:

  • Improved performance by reducing memory usage when using array_map() on large arrays. Support for nullable types was added. The callback function can now specify nullable types for its arguments.

PHP 7.2.0:

  • The ability to specify keys in the resulting array was introduced. A third parameter can be passed to array_map() to specify an array of keys to be used for the result. If the array of keys is shorter than the result array, the remaining elements will be indexed numerically.

PHP 7.3.0:

  • Performance improvements for array_map() on large arrays. Support for iterable type hinting was added, allowing the callback function to accept any iterable object, such as arrays or objects implementing the Traversable interface.

PHP 8.0.0:

  • Improved performance and reduced memory usage for array_map() on large arrays. array_map() can now handle named arguments. Instead of passing the callback as a separate argument, it can be specified using the fn keyword followed by the callback.

PHP 8.1.0:

  • Further performance improvements for array_map(). These are some of the notable changes and additions to array_map() in different PHP versions. Remember that this is not an exhaustive list, and there may be other minor changes and bug fixes not mentioned here. It's always a good practice to consult the official PHP documentation for the most up-to-date information on array_map()` and its behavior in different PHP versions.

Examples

Creating an Array of Arrays Using array_map()

Here's an example of using array_map() to create an array of arrays in PHP:

Output

Explanation

In the above example, we have three separate arrays: names,names, ages, and $countries, each containing corresponding values. Using array_map(), we pass an anonymous function as the callback that takes elements from all three arrays and combines them into a new array. The resulting array, stored in the $result variable, contains arrays with the keys 'name', 'age', and 'country', representing the data from the original arrays. Finally, we print the resulting array using print_r() to visualize the array of arrays. Run the above code in your editor for a better and clear explanation.

User-made Function to Change the Values of an Array

Here's an example of a user-made function that changes the values of an array in PHP:

Output

This code demonstrates a function called changeArrayValues that takes an array and a callback function as parameters. The function modifies the values of the array by applying the callback function to each element. Run the above code in your editor for a better and clear explanation.

Using two Arrays

Here's an example of using array_map() with two arrays in PHP:

Output

Explanation

In the above example, we have two separate arrays: $numbers1 and $numbers2, each containing corresponding numeric values. Using array_map(), we pass an anonymous function as the callback that takes elements from both arrays and performs addition on them. The resulting array, stored in the $result variable, contains the sum of the corresponding elements from both arrays. Finally, we print the resulting array using print_r() to visualize the output. Run the above code in your editor for a better and clear explanation.

Change all Letters of the Array Values to Uppercase

Here's an example of using array_map() to change all the letters of the array values to uppercase in PHP:

Output

Explanation

In the above example, we have an array called fruitswithlowercasefruitnames.Usingarraymap(),wepassthebuiltinfunctionstrtoupperasthecallback.Thestrtoupperfunctionconvertsastringtouppercase.Theresultingarray,storedinthefruits with lowercase fruit names. Using `array_map()`, we pass the built-in function strtoupper as the callback. The strtoupper function converts a string to uppercase. The resulting array, stored in the uppercaseFruits variable, contains the fruit names with all letters converted to uppercase. Finally, we print the resulting array using print_r() to visualize the output. Run the above code in your editor for a better and clear explanation.

Using the PHP array_map() with an Array of Objects

Here's an example of using array_map() with an array of objects in PHP:

Output

Explanation

In the above example, we have a class Person that represents a person with name and age properties. We create an array of Person objects named people.Wedefineacallbackfunction,people. We define a callback function, getName, which extracts the name property from each Person object. Using array_map(), we apply the getNamefunctiontoeachobjectinthegetName function to each object in the people array, which results in a new array of $names containing only the names extracted from the objects. Run the above code in your editor for a better and clear explanation.

Finally, we print the $names array using print_r() to visualize the output.

Assign null as the function name

Output

Explanation

In the above example, we pass an anonymous function as the callback in array_map(). This anonymous function takes each element numfromthenum from the `numbers` array and returns null for each element. As a result, the resulting array $result contains null values for each element of the original array. Run the above code in your editor for a better and clear explanation.

Conclusion

  • array_map is a powerful function in PHP that allows developers to transform and manipulate arrays easily.
  • It applies a callback function to each element of an array and returns a new array with the transformed values.
  • array_map eliminates the need for explicit loops and reduces code complexity.
  • It is versatile and can be used for various tasks such as calculations, string transformations, and extracting specific values.
  • array_map has been available in PHP since version 4.0.6 and continues to be supported in the latest PHP versions.
  • Over the years, PHP versions have introduced enhancements to array_map, such as support for multiple arrays, anonymous functions, performance optimizations, nullable types, and named parameters.
  • array_map is widely used in PHP programming to streamline array manipulation and improve productivity.