calculate the difference of each values of array

后端 未结 2 640
名媛妹妹
名媛妹妹 2021-01-23 12:46

Newbie here in PHP programming. I have some question regarding arrays. How can I get the difference between adjacent values in an array?

$value = array(2, 5, 9,          


        
相关标签:
2条回答
  • 2021-01-23 13:16

    @Gumbo you added $diffs = array(); it has to be $value

    <?php
    $value = array(2,5,9,10,19);
    for ($i = 1, $n = count($value); $i < $n; $i++) {
        $diffs[] = $value[$i] - $value[$i-1];
    }
    
    echo "<pre>";
    print_r($diffs);
    echo "</pre>";
    ?>
    
    0 讨论(0)
  • 2021-01-23 13:22

    Just use a simple for loop:

    $diffs = array();
    for ($i = 1, $n = count($value); $i < $n; $i++) {
        $diffs[] = $value[$i] - $value[$i-1];
    }
    
    0 讨论(0)
提交回复
热议问题