How to check if a sequence of numbers is an Arithmetic progression (consecutive differences are the same) in PHP

1 Answer

0 votes
function isArithmeticProgression($arr) {
    $size = count($arr);
    if ($size == 1) {
        return true;
    }

    sort($arr);

    $difference = $arr[1] - $arr[0];
    for ($i = 2; $i < $size; $i++) {
        if ($arr[$i] - $arr[$i - 1] != $difference) {
            return false;
        }
    }

    return true;
}

$arr = array(10, 20, 15, 5, 25, 35, 30);

echo isArithmeticProgression($arr) ? "Yes" : "No";



/*
run:
 
Yes
 
*/

 



answered Sep 21, 2024 by avibootz
edited Sep 22, 2024 by avibootz
...