Hasan
Hasan

Reputation: 159

PHP Array: Calculate difference among values in same array

I am trying to compute the difference between all values in an array and store them (the differences) in a single array.

An ideal example would be something like this:

<?php

$data = array('1', '5', '12');

// Compute the difference between each value with another value.

?>

And then I like to have the following results in an array:

4, 11, 7

How can I achieve it?

Upvotes: 0

Views: 1458

Answers (2)

Mauricio Florez
Mauricio Florez

Reputation: 1132

Check this https://3v4l.org/9oiqs

$data = [1, 5, 12, 15, 20, 25,];

function getDifferences($aValues)
{
    $aDiff = [];
    $iSize = count($aValues);
    for ($i = 0; $i < $iSize; $i++)
    {
        for ($j = $i + 1; $j < $iSize; $j++)
        {
            $aDiff[$aValues[$i]][] = abs($aValues[$i] - $aValues[$j]);
        }
    }
    return $aDiff;
}

function printDifferences($aValues){
    foreach ($aValues as $iNumber => $aDiffs){
        echo "Differences for $iNumber: " . implode(', ', $aDiffs) . PHP_EOL;
    }
}

$aDiff = getDifferences($data);
printDifferences($aDiff);

Result
Differences for 1: 4, 11, 14, 19, 24
Differences for 5: 7, 10, 15, 20
Differences for 12: 3, 8, 13
Differences for 15: 5, 10
Differences for 20: 5

Upvotes: 0

musashii
musashii

Reputation: 445

try this

$data = array('1', '5', '12');
$differences=[];
for($i=0;$i<count($data);$i++){
    for($j=$i+1;$j<count($data);$j++){
        $differences[]=abs($data[$i]-$data[$j]);
    }
}
print_r($differences);

results in

Array
(
    [0] => 4
    [1] => 11
    [2] => 7
)

Upvotes: 2

Related Questions