PHP array_map Function | Modify Array In PHP

Using loops is one of the most basic concepts taught to a novice programmer. We always come up with a loop solution for any trivial task because we are accustomed to them. However, a more experienced programmer might write a solution without actually looping through the array using an inbuilt defined function. The PHP array_map function is an inbuilt PHP function that sends the array elements to a user-defined function.

In this article, I will discuss the PHP array_map Function to modify the array in PHP.

What Is array_map Function?

array_map — Applies the callback to the elements of the given arrays

http://php.net

The PHP array_map function is an inbuilt PHP function that sends the array elements to a user-defined function. It helps to modify the contents of an array using the user-defined function and returns the modified array as output.

Syntax

array_map(callbackFunction,arr1,arr2…)

Parameters

The array_map function takes in two mandatory parameters; callbackFunction and an array. The rest of the parameters are optional.

  • callbackFunction: The callback Function is a mandatory user-defined function passed to the array_map function according to which the array elements will be modified.
  • $arr1: The array arr1 is a mandatory array which will be modified by the callback function.
  • $arr2..$arrn: You can pass more than one array to the PHP array_map Function.

Examples

Let’s consider the following examples to understand more.

Example 1: Basic Usage with Integers

If you need to calculate the squares of all the numbers given in an array, this is what you might possibly code using a foreach loop:

<?php
	$testNum = array(1,2,3,4,5);
	foreach($testNum as $key => $num) {
		$testNum[$key] = $num*$num;
	}
	print_r($testNum);
	/* Output:
		Array
		(
		    [0] => 1
		    [1] => 4
		    [2] => 9
		    [3] => 16
		    [4] => 25
		)
	*/
?>

The array_map function can be used to implement the same solution as follows:

<?php
	
	function calculateSquares($num) {
		return $num*$num;
	}
	
	$testNum = array(1,2,3,4,5);
	$testNum = array_map('calculateSquares', $testNum);
	print_r($testNum);
	/* Output:
		Array
		(
		    [0] => 1
		    [1] => 4
		    [2] => 9
		    [3] => 16
		    [4] => 25
		)
	*/
?>

We can also use Lambda Functions to implement the same logic as shown below:

<?php
	$lambdaFunc = function($num) {
		return $num * $num;
	};
	
	$testNum = array(1,2,3,4,5);
	$testNum = array_map($lambdaFunc, $testNum);
	print_r($testNum);
	/*
	Array
		(
		    [0] => 1
		    [1] => 4
		    [2] => 9
		    [3] => 16
		    [4] => 25
		)
	*/
?>

Example 2: Calling a Class Method

If the method you are calling is a class method, then you can use the array_map function by passing the object reference with the method name as shown in the following example:

<?php

	class TestArrayMap {

		private function calculateSquares($num) {
			return $num * $num;
		}

		public function getSquares($testNumArray) {
                        //Object reference passed along with method name
			return array_map(array($this, 'calculateSquares'), $testNumArray);
		}

	}

	$testArrayMapObj = new TestArrayMap();
	print_r($testArrayMapObj->getSquares(array(1,2,3,4,5)));
?>

Example 3: Pre Defined PHP Functions

You may also pass PHP predefined functions as the callback method instead of creating user-defined functions. Here, we are calling the inbuilt PHP strtoupper Function.

<?php
	$stringArray = array('bringing', 'knowledge', 'together');
	$upperCaseArray = array_map('strtoupper', $stringArray);
	print_r($upperCaseArray);
	/*
		Array
		(
		    [0] => BRINGING
		    [1] => KNOWLEDGE
		    [2] => TOGETHER
		)
	*/
?>

Example 4: Null Callback

On passing null as the callback function, array_map merges two arrays in the following way:

<?php
	$userNames = array('Vishesh', 'Sam', 'Joe');
	$userEmails = array('[email protected]', '[email protected]', '[email protected]');
	print_r(array_map(null, $userNames, $userEmails));
	/*
	Array
	(
	    [0] => Array
	        (
	            [0] => Vishesh
	            [1] => [email protected]
	        )

	    [1] => Array
	        (
	            [0] => Sam
	            [1] => [email protected]
	        )

	    [2] => Array
	        (
	            [0] => Joe
	            [1] => [email protected]
	        )

	)
	*/
?>

Performance Analysis

You might be wondering is a for loop is faster than using the PHP array_map function in terms of processing time. I performed a performance analysis on PHP 7.2 and found that the PHP array_map Function has almost the same performance as a regular for loop.

I performed the analysis by calculating the time required to calculate squares of all numbers from 1 to 1000000 using both array_map and a foreach loop. The code I used for calculting time difference is as follows:

<?php
	/* ############## Array Map ################### */
	function calculateSquares($num) {
		return $num*$num;
	}
	$startTime = microtime(true);
	$testNum = range(1,1000000);
	$newArr = array_map('calculateSquares', $testNum);
	$endTime = microtime(true);
	echo 'Time Taken By array_map: '.($endTime - $startTime);

        /* ############## For Loop #################### */
	$startTimeLoop = microtime(true);
	$testNum = range(1,1000000);
	$newArr = array();
	foreach($testNum as $key => $value) {
		$newArr[] = $value * $value;
	}
	$endTimeLoop = microtime(true);
	echo '<br/>Time Taken by Loop: '.($endTimeLoop - $startTimeLoop);
?>
PHP array_map function vs foreach loop
Graph showing performance analysis of array_map vs foreach loop

As shown in the above test results the PHP array_map Function almost performs equally good as a regular foreach loop for performing the same task. However, using array_map looks better in the source code. It reduces the number of for-loops you have to write and performs the same task.

Conclusion

In this article, we discussed the use of PHP array_map function for modifying elements in an array. I also did a performance analysis for checking the time taken by a traditional for loop and using the array_map function.

You can also read more about array_map function on the official PHP documentation. Please read more articles on PHP on Concatly. Kindly leave your valuable comments below to help me improve this resource.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *