Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
why "3"=>"go" how you get that? – Akam Jul 17 at 23:31
would it be ..."3"=>"go","4"=>"stop" instead of "3"=>"go","7"=>"stop")? – Sean Jul 17 at 23:37
yes sean sorry it should have been "4"=>"stop" – Wajid Abbasi Jul 17 at 23:46
Is it not possible to consider not putting the duplicates in the array to begin with? – calcinai Jul 18 at 0:16
possible duplicate of php multi-dimensional array remove duplicate – hakre Jul 18 at 22:18
add comment (requires an account with 50 reputation)

2 Answers

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 at 23:41
+1 for nice style :) – Akam Jul 17 at 23:49
Nice to hear it helped ;-) – UrGuardian4ngel Jul 17 at 23:51
add comment (requires an account with 50 reputation)

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 at 23:26
$new_val would be the value you're adding eg. "stop" or "go" – calcinai Jul 17 at 23:27
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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