4

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");
4
  • why "3"=>"go" how you get that? Commented Jul 17, 2013 at 23:31
  • would it be ..."3"=>"go","4"=>"stop" instead of "3"=>"go","7"=>"stop")? Commented Jul 17, 2013 at 23:37
  • yes sean sorry it should have been "4"=>"stop" Commented Jul 17, 2013 at 23:46
  • Is it not possible to consider not putting the duplicates in the array to begin with? Commented Jul 18, 2013 at 0:16

2 Answers 2

9

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

can you further elaborate on $new_val where would it come from?
$new_val would be the value you're adding eg. "stop" or "go"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.