How to pass additional parameters in array_map PHP function

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Pass additional parameters in array_map PHP Code Examples

The array_map PHP callback cannot access variables outside its scope by default. So, PHP features the “use” keyword, enabling developers to pass more parameters to the function. The article tries to explain it without diving into complexities.

Introduction – array_map PHP

The array_map PHP is a higher order function. A higher order function takes another function, known as a callback function usually. Higher order functions are eminent in programming languages like Javascript and Python, but they have also made their way to more conventional languages like PHP and Java.

array_map PHP

We have done an in-depth article about this function, and it is suggested to go through it before proceeding to have a solid ground. This article also reviews PHP array_map before jumping in straight to the subject of how to pass additional parameters in the array_map PHP function.

Have you tried any of the following highly relevant Pluralsight PHP Courses?

We love Pluralsight because it has thousands of high-quality course content and is extremely affordable. You don’t have to pay for individual courses. It’s a really small monthly membership and you get access to the entire catalog. You can track and review all of your progress and also obtain additional certifications.

Courses

  • PHP Design Patterns
  • PHP: The Big Picture
  • PHP 8: Web Application Security
  • High-Performance PHP
  • Object-Oriented PHP

Learning Paths:

  • PHP Development Fundamentals

Pluralsight Free Trial

Curious about Pluralsight but not ready to commit? We understand. We were able to get a free trial for you to test-drive and see all of their courses. Click on the link below

Try a Pluralsight free trial for 7 days!

PHP array_map – A review

array_map(?callable $callback, array $array, array …$arrays): array

The array map function takes an optional callback function. The function applies to all the elements of an array or arrays if more than one is provided. The callback function maps these elements based on the callback implementation. The implementation could be as simple as simple addition or involve a more complex logic.

array_map PHP

Here’s an example of the array_map function with a callback that multiplies numeric array elements by two.

<?php
$arr = [1, 2, 3, 4, 5];
 
$mapped_arr = array_map
                  (
                     function($elem){ return $elem * 2;},
                     $arr
                  );
 
print_r($mapped_arr);
 
/*
OUTPUT
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
*/
?>

Pass additional parameters in array_map with callback parameters

There could be more than one array involved. The arguments count in the callback function should ideally be equal to the numbers of arrays passed. The example shows it more clearly.

<?php
$roman_numerals = ["I", "II", "III", "IV", "V"];
$english_numbers = ["One", "Two", "Three", "Four", "Five"];
 
$mapped_arr = array_map
            (
               fn($rom, $eng) => "The Roman Numeral {$rom} is {$eng} in English",
               $roman_numerals,
               $english_numbers
            );
 
 
/*
OUTPUT
Array
(
    [0] => The Roman Numeral I is One in English
    [1] => The Roman Numeral II is Two in English
    [2] => The Roman Numeral III is Three in English
    [3] => The Roman Numeral IV is Four in English
    [4] => The Roman Numeral V is Five in English
)
*/
?>

The callback takes two arguments: one for the Roman numerals, another for the English numbers.

Example#3 – Zip Operation

Another cool feature of this function is that it does a zip operation without a callback function. A zip operation is grouping the elements of the same index. Here’s an example of zip operation with array_map in PHP.

<?php
$roman_numerals = ["I", "II", "III", "IV", "V", "VI"];
$english_numbers = ["One", "Two", "Three", "Four", "Five", "Six"];
$numbers = [1, 2, 3, 4, 5, 6];
 
print_r(array_map(null, $roman_numerals, $english_numbers, $numbers));
 
/*
OUTPUT
Array
(
    [0] => Array
        (
            [0] => I
            [1] => One
            [2] => 1
        )
 
    [1] => Array
        (
            [0] => II
            [1] => Two
            [2] => 2
        )
 
    [2] => Array
        (
            [0] => III
            [1] => Three
            [2] => 3
        )
 
    [3] => Array
        (
            [0] => IV
            [1] => Four
            [2] => 4
        )
 
    [4] => Array
        (
            [0] => V
            [1] => Five
            [2] => 5
        )
 
    [5] => Array
        (
            [0] => VI
            [1] => Six
            [2] => 6
        )
 
)
*/
?>

So, that’s alot for a review. Let’s move on to the topic of the article.

Additional parameters in array_map PHP function

Example#2 has clarified the array_map callback parameters and their variation with the numbers of arrays. There’s a way to use variables in the callback function outside its scope. This practice is often necessary for scenarios where we need more control over the arguments of a callback function.

PHP features the “use” keyword for introducing local variables in a callback function. Let’s see an example of that before seeing array_map with use.

PHP use keyword example

Here’s an example of the “use” keyword forming a closure. A closure is a function that returns an inner function that can access the parent function’s scope. The inner function keeps these references even after the parent function has been executed.

<?php
 
function increment($x) {
   $add_constant = $x;
 
   return function() use (&$add_constant) {
      return $add_constant++;
   };
}
 
$incrementer = increment(0);
echo $incrementer(); //returns 0;
echo $incrementer(); //returns 1;
echo $incrementer(); //returns 2;
 
?>

Closures can be confusing at first, but they are all about function scopes. Also, the use takes a variable by value, meaning it won’t modify the original value. To alter this behavior, pass the variable by reference, as shown in the example.

The array_map with use example

Let’s see an example of array_map with use.

<?php
$greetings = "Hi";
$names_arr = [
   "Joe",
   "Tena",
   "Jacob",
   "Laila"
];
 
$names_with_greetings = array_map(function($name) use ($greetings) {
   return $greetings.' '.$name;
}, $names_arr);
 
print_r($names_with_greetings);
 
/*
OUTPUT
Array
(
    [0] => Hi Joe
    [1] => Hi Tena
    [2] => Hi Jacob
    [3] => Hi Laila
)
*/
?>


So, the array_map PHP callback accesses a variable $greetings from the outside scope. The function uses the value and prepends it to every name from the $names_arr. As the following example shows, this wouldn’t have been possible without the array_map with use.

<?php
$greetings = "Hi";
$names_arr = [
   "Joe",
   "Tena",
   "Jacob",
   "Laila"
];
 
$names_with_greetings = array_map(function($name) {
   return $greetings.' '.$name;
}, $names_arr);
 
print_r($names_with_greetings);
 
/*
OUTPUT
PHP Warning:  Undefined variable $greetings
*/
?>

PHP issues a warning saying that the variable $greetings is undefined. That’s because the callback function cannot access the outer scope without the use keyword. 

Conclusion

The article gives a thorough overview of array_map PHP and explains array_map callback parameters. These parameters vary with the number of arrays passed to the function. However, accessing variables outside the scope of the callback is not that straightforward. So, PHP features the “use” keyword, and the article explains it as well. Finally, we see the array_map with use, which sums up everything. I hope it has been some fun learning. Stay tuned to more at FuelingPHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.