1

Here's an example in plain english of what I am trying to achieve: if the number given is 4, then I want to add 1 to every value that is equal to or less than 4 into the corresponding index of another array. (hope that makes sense)

So my first array looks like this:

Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 4 [4] => 3 [5] => 2 [6] => 9 [7] => 8 [8] => 1 [9] => 10 [10] => 11 [11] => 12 [12] => 13 [13] => 14 [14] => 15 [15] => 16 [16] => 17 [17] => 18 ) 

The second array looks like this:

Array ( [0] => 4 [1] => 3 [2] => 4 [3] => 4 [4] => 4 [5] => 5 [6] => 4 [7] => 4 [8] => 5 [9] => 4 [10] => 4 [11] => 5 [12] => 5 [13] => 4 [14] => 4 [15] => 4 [16] => 3 [17] => 3 ) 

And I am wanting the second array to look like this (after adding 1 to every value below 4 in the first array) so after the addition it would be

Array ( [0] => 4 [1] => 3 [2] => 4 [3] => 5 [4] => 5 [5] => 6 [6] => 4 [7] => 4 [8] => 6 [9] => 4 [10] => 4 [11] => 5 [12] => 5 [13] => 4 [14] => 4 [15] => 4 [16] => 3 [17] => 3 ) 

In which index 3,4,5,9 have changed.

1
  • How is the first array used in all of this? Shouldn't index 8 (instead of 9) be updated? Commented Mar 28, 2014 at 6:31

2 Answers 2

3

I think you're looking for array_map

function increase( $m, $n )
{
  if( $m < 4 )
  {
   return $n+1;
  }
  return $n
}

$arr1;
$arr2;

print_r( array_map("increase", $arr1, $arr2 ) );

Note: this will return a new array.

Sign up to request clarification or add additional context in comments.

Comments

1

Using an array_walk

array_walk($arr2,function(&$v,$k) use($arr1) { if($arr1[$k]<=$v){ $v=$v+1;} });

Demo

[or]

A simple foreach will do

foreach($arr1 as $k=>$v)
{
    if($v<=$arr2[$k])
    {
        $arr2[$k]=$arr2[$k]+1;
    }
}
print_r($arr2);

Demo

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.