I want to get the difference between the values of a array.
<?php
$array_values = array('2', '6', '16', '27');
?>
my expectation would be:
Array
(
[0] => 4
[1] => 10
[2] => 11
)
The code:
<?php
$array_data = array('2', '6', '16', '27');
$differences=[];
for($i=0;$i<count($array_data);$i++){
for($d=$i+1;$d<count($array_data);$d++){
$differences[]=abs($array_data[$i]-$array_data[$d]);
}
}
print_r($differences);
?>
What i get:
Array ( [0] => 4 [1] => 14 [2] => 25 [3] => 10 [4] => 21 [5] => 11 )
The only examples that i found in the web was the difference of two arrays or the difference between each value with another value. But i could not find any examples where the difference will be calculatet ONLY with the next value in the array.
Any hint how i could solve that?
thanks.
3
Answers
This can be done fairly easily, assuming the array is always in the correct order.
Small explanation:
If it is the first one, we have nothing to compare it to so we can continue to the next iteration.
Then for each one after that we get the value of the current iteration and the previous iteration and we calculate the solution, and add it to the array.
Alternative solution if you don’t want the continue step, then you’ve to be sure that the array contains at least 2 values:
It can be tested here.
https://3v4l.org/AO9mi
Steps of array_reduce with [ ‘2’, ‘6’, ’16’, ’27’ ]:
How about this one? I’ve optimized the loop and used short-hand notation for arrays and the pushing.
In the loop, we can start at element
0
and since the last element in the array needs another "next" element to calculate a diff, we can just skip this element by reducing the loop cycle by one step, thus:If
$array_data
consists only of one element like['2']
for example, it will not yield any difference. You need to provide at least two entries in the array.However, it is possible to also define values for entries that don’t exist in the array (index out of bounds) by providing a default e.g.
this way you could assume e.g.
0
for non-existing elements. The delta would then beArray([0] => 2)
for['2']
.