Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing successive duplicate occurrences in an array

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");
like image 746
Abbasi Avatar asked Dec 27 '22 00:12

Abbasi


1 Answers

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;
}
like image 63
UrGuardian4ngel Avatar answered Jan 14 '23 06:01

UrGuardian4ngel