简体   繁体   中英

How to get subtraction between next and prev values in PHP array

I have got array with data like this:

$array = [0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25];

What I want to get is array of absolute subtraction values between next value and prev:

[0.0-0.19, 0.19-0.5, 0.5-0.75, 0.75-1.0, 1.0-1.25, 1.25-1.50, 1.5-1.75, 1.75-2.0, 2.0-2.25]

Result should be an array with absolute values like:

$result = [0.19, 0.31, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25];

Maybe there's any native function or good looking solution?

Try iterating like this :

$array = [0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25];

$result = [];
for ($i = 1; $i < count($array); $i++) {
    $result[] = abs($array[$i - 1] - $array[$i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM