waqas
waqas

Reputation: 91

Handle multiple parameters in array_map call back

I have the following code:

$a=array(15,12,13,25,27,36,18);
$b=array(1,1,1,1,1,1,1);//is it possible to pass only one value=1, instead of array containing seven 1's
// expectation: $b = array(1); or $b= 1; 
//instead of $b=array(1,1,1,1,1,1,1);

function array_add($p,$q){
   return($p+$q);
}
$c=array_map("array_add",$a,$b);

I want something like:

$a=array(15,12,13,25,27,36,18);
$b=array(1);

function array_add($p,$q){
   return($p+$q);
}
$c=array_map("array_add",$a,$b);

Any better solution thanks.

Upvotes: 2

Views: 1278

Answers (2)

msfoster
msfoster

Reputation: 2572

Have a look at array_walk

From Your example, it would be:

function array_add( &$item, $key, $toAdd) { 
   $item+=$toAdd;
}
array_walk($a, 'array_add', 1);

I would also recommend that you have a look at the answer provided using closure(use)

Upvotes: 0

LF-DevJourney
LF-DevJourney

Reputation: 28529

You can use array_map as this, and pass the $param2 with use()

array_map(function($v) use($param2){
    //do something
}, $input);

Upvotes: 1

Related Questions