Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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.

share|improve this question

marked as duplicate by hakre, Ocramius, tereško, Orangepill, Graviton Aug 12 '13 at 12:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
why "3"=>"go" how you get that? –  user1646111 Jul 17 '13 at 23:31
    
would it be ..."3"=>"go","4"=>"stop" instead of "3"=>"go","7"=>"stop")? –  Sean Jul 17 '13 at 23:37
    
yes sean sorry it should have been "4"=>"stop" –  Wajid Abbasi Jul 17 '13 at 23:46
    
Is it not possible to consider not putting the duplicates in the array to begin with? –  calcinai Jul 18 '13 at 0:16

2 Answers 2

up vote 5 down vote accepted

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;
}
share|improve this answer
    
Thanks a lot worked like a charm :) –  Wajid Abbasi Jul 17 '13 at 23:41
    
+1 for nice style :) –  user1646111 Jul 17 '13 at 23:49
    
Nice to hear it helped ;-) –  UrGuardian4ngel Jul 17 '13 at 23:51

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

share|improve this answer
    
can you further elaborate on $new_val where would it come from? –  Wajid Abbasi Jul 17 '13 at 23:26
    
$new_val would be the value you're adding eg. "stop" or "go" –  calcinai Jul 17 '13 at 23:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.