-1

I would like to update the values of a multidimensionnal php array : $a

array(1) { 
["test"]=> array(4) { 
[0]=> int(5) 
[1]=> int(7) 
[2]=> int(10) 
[3]=> int(14) 
} 
}

For $a["test"][$i], I would like to obtain this new value $a["test"][$i] - $a["test"][$i-1].

In this case the resulting array would be :

array(1) { 
["test"]=> array(4) { 
[0]=> int(5) 
[1]=> int(2) 
[2]=> int(3) 
[3]=> int(4) 
} 
}

Of course, I could do it with a foreach loop and a new array

$new = array();
foreach($a as $k=>$v){
for($i=0;$i<=3;$i++){
$new[$k][$i] = $v[$i] - $v[$i-1];
}
}
$a = $new;
var_dump($a);

but is this the best way? Just out of curiosity, I was wondering if using array_walk to make it could be nicer and, generally, how/if array_walk could access the previous/next value in the array.

Thank you a lot !

Abanoub Makram
  • 463
  • 2
  • 13
user1719210
  • 310
  • 3
  • 11

2 Answers2

0

PHP code demo

<?php

$array = array(
    "test" => array(5, 7, 10, 14)
);
$new=array();
array_walk($array["test"], function($value,$key) use (&$new,&$array){
    if($key>0)
    {
        $new["test"][]=$array["test"][$key]-$array["test"][$key-1];
    }
    else
    {
        $new["test"][]=$value;
    }
});
print_r($new);

Or:

PHP code demo

<?php
$array = array(
    "test" => array(5, 7, 10, 14)
);
$newArray=array();
foreach($array["test"] as $key => $value)
{
    if($key>0)
    {
        $newArray["test"][]=$array["test"][$key]-$array["test"][$key-1];
    }
    else
    {
        $newArray["test"][]=$value;
    }
}
print_r($newArray);
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

Since you're overwriting the original array with the new values in the end anyway, you might as well just change the values of the original array as you go.

A custom function can do the successive subtraction for each subset.

function successive_subtraction(&$array) {
    $subtrahend = 0;               // store the previous value for subtraction
    foreach ($array as &$value) {
        $temp = $value;            // store the current value in a temporary variable
        $value -= $subtrahend;     // subtract the previous value
        $subtrahend = $temp;       // original current value become new previous value
    }
}

Then apply that function to each element of the outer array with array_walk.

array_walk($a, 'successive_subtraction');

This code is actually more complex that the way you're already doing it. The main advantage to modifying the existing array rather than creating a modified copy and then overwriting it would be less peak memory usage, but if the arrays you're dealing with aren't very large, then that shouldn't really be a problem, and I would say just keep it simple.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80