Skip to content
Advertisement

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");

Advertisement

Answer

You can just do something like:

if(current($a) !== $new_val)
    $a[] = $new_val;

Assuming you’re not manipulating that array in between you can use current() it’s more efficient than counting it each time to check the value at count($a)-1

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement