2

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.

2
  • What are you trying to do? Please provide an example With expected behaviour. Commented Jul 4, 2017 at 7:20
  • $a=array(15,12,13,25,27,36,18); $b=array(1,1,1,1,1,1,1); // I want to use one value for all indexes instead of array i.e. $b = 1; function array_add($p,$q){ return($p+$q); } $c=array_map("array_add",$a,$b); Commented Jul 4, 2017 at 7:54

2 Answers 2

1

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

array_map(function($v) use($param2){
    //do something
}, $input);
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.