How to group all differences between consecutive numbers from associative array? Below is the array which I’m using
need to group (2,3)(7,8) with they difference , ignore (11,6,5,9)
$array = array(
2 =>"12",
3 =>"12",
11 => "16",
6 => "15",
5 => "14",
7 => "16",
8 => "17",
9 => "18")
Below is the code which I’m using to group the array, but it’s not working:
foreach ($array as $k => $v) {
echo $prev;
if (isset($prev)) {
if (($v - $prev) != 1) $newArray[] = $v;
} else { $newArray[] = $v; }
$prev = $v;
}
echo '<pre>';
print_r($newArray);
Currently I’m getting this:
Array
(
[0] => 12
[1] => 12
[2] => 16
[3] => 15
[4] => 16
)
but I need the O/P to be (2,3)=0 difference, (7,8)=1 difference, i. e.
array(
[0]=>0,
[1]=>1
);
So here you go.
This produces the array for three consecutive pairs:
If you want to stop after two pairs, add a running counter
$i = 0;before theforeachand exit withif (++$i >= 2) break;inside theifin the loop: