Is there any way that I can remove the successive duplicates from the array below while only keeping the first one?
The array is shown below:
$a=array("1"=>"go","2"=>"stop","3"=>"stop","4"=>"stop","5"=>"stop","6"=>"go","7"=>"go","8"=>"stop");
What I want is to have an array that contains:
$a=array("1"=>"go","2"=>"stop","3"=>"go","7"=>"stop");
Successive duplicates? I don't know about native functions, but this one works. Well almost. Think I understood it wrong. In my function the 7 => "go" is a duplicate of 6 => "go", and 8 => "stop" is the new value...?
function filterSuccessiveDuplicates($array)
{
$result = array();
$lastValue = null;
foreach ($array as $key => $value) {
// Only add non-duplicate successive values
if ($value !== $lastValue) {
$result[$key] = $value;
}
$lastValue = $value;
}
return $result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With