skip to Main Content

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


  1. 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.

    <?php
    $array_data = array('2', '6', '16', '27');
    $differences=[];
    for($i=0;$i<count($array_data);$i++) {
        if($i == 0) continue;
        array_push($differences, $array_data[$i] - $array_data[$i - 1]);
    }
    print_r($differences);
    
    ?> 
    

    Alternative solution if you don’t want the continue step, then you’ve to be sure that the array contains at least 2 values:

    <?php
    $array_data = array('2', '6', '16', '27');
    $differences=[];
    for($i=1;$i<count($array_data);$i++) {
        array_push($differences, $array_data[$i] - $array_data[$i - 1]);
    }
    print_r($differences);
    
    ?> 
    

    It can be tested here.

    Login or Signup to reply.
  2. $values = [ '2', '6', '16', '27' ];
    
    $result =
      array_reduce(
        array_slice($values, 1),
        fn($carry, $curr) => [
          'diff' => [ ...$carry['diff'], abs($curr - $carry['prev']) ],
          'prev' => $curr
        ],
        [ 'diff' => [], 'prev' => $values[0] ?? null ]
      )['diff'];
    
    print_r($result);
    

    https://3v4l.org/AO9mi

    Steps of array_reduce with [ ‘2’, ‘6’, ’16’, ’27’ ]:

    // $array arg is:           [ '6', '16', '27' ]
    // $initial arg is:         [ 'diff' => [], 'prev' => '2' ]
    
    // the first call returns:  [ 'diff' => [ 4 ], 'prev' => '6' ]
    // the second call returns: [ 'diff' => [ 4, 10], 'prev' => '16' ]
    // the third call returns:  [ 'diff' => [ 4, 10, 11 ], 'prev' => '27' ]
    
    // and at the end we grab value with ['diff']
    
    Login or Signup to reply.
  3. How about this one? I’ve optimized the loop and used short-hand notation for arrays and the pushing.

    <?php
    
    $array_data = ['2', '6', '16', '27'];
    $differences = [];
    
    for ($i = 0; $i < sizeof($array_data) - 1; $i++) {
        $differences[] = abs($array_data[$i + 1] - $array_data[$i]);
    }
    
    # debug
    print_r($differences);
    

    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:

    $i < sizeof($array_data) - 1;
    

    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.

    $array_data[$i + 1] ?? 0
    

    this way you could assume e.g. 0 for non-existing elements. The delta would then be Array([0] => 2) for ['2'].

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search