0

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?

3
  • What do you mean for difference, next, previous, absolute value, sum of all elements? Commented Dec 9, 2017 at 19:06
  • @MauricioFlorez I mean the difference between 5 & 1 (which is 4). And then the difference between 1 & 12 (which is 11).. and so on. Commented Dec 9, 2017 at 19:33
  • Related: calculate the difference of each values of array Commented Sep 7, 2023 at 11:25

2 Answers 2

2

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
)
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Little variation from @musashii

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.