php array removing successive duplicate occurances in an array

The question i would like to ask here is:

Is there anyway 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");

Any suggestions would help. Regards.

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

Leave a Reply

Your email address will not be published. Required fields are marked *