I have following code to remove adjacent duplicates from an array
$myArray = array(
0 => 0,
1 => 0,
2 => 1,
5 => 1,
6 => 2,
7 => 0,
8 => 0,
);
$previtem= NULL;
$newArray = array_filter(
$myArray,
function ($currentItem) use (&$previtem) {
$p = $previtem;
$previtem= $currentItem;
return $currentItem!= $p ;
}
);
echo "<pre>";
print_r($newArray);
Problem
Required Output.
Array
(
[0] => 0
[2] => 1
[6] => 2
[7] => 0
)
Actual output
Array
(
[2] => 1
[6] => 2
[7] => 0
)
How to get required output without modifying my code much?? or is there any other better way?
Thanks
The problem is the loose comparison in your filter function. When you say
return $currentItem != $p ;
PHP is treating the initial null value of $p
and the 0 value of $currentItem
as equivalent, so the first iteration gets filtered out.
If you change the line to use strict comparison instead (===
or !==
), it will work as expected
return $currentItem !== $p ;
This ensures only adjacent values that are exactly the same, including type comparison, are filtered.