1
$arr = array(1, 2, '...', '...', '...', 6, 7, 8, '...', 10);
array_unique creates: array(1, 2, '...', 6, 7, 8, 10);
I want the following: array(1, 2, '...', 6, 7, 8, '...', 10);

So basically, I'm looking for a fast way to remove only duplicates next to eachother.

1
  • 1
    AFAIK, no out of the box function for it, so write a small looping script. Commented Sep 30, 2014 at 15:20

2 Answers 2

1
$result = array();
$first = true;
foreach ($array as $x) {
    if ($first || $x !== $previous) $result[] = $x;
    $previous = $x;
    $first = false;
}

Alter the $x !== $previous condition to suit your preferred definition of "duplicate". For example, array_unique does a loosely-typed comparison.

Sign up to request clarification or add additional context in comments.

2 Comments

You need to set $first back to true when you encounter a non-duplicate.
@Barmar No, that's not what it's for.
0

I would do it this way:

<?php

$arr = array(1, 2, '...', '...', '...', 6, 7, 8, '...', 10);

$el = $arr[0];

$out = $arr;

for ($i=1, $c = count($out); $i<$c; ++$i) {
    if ($arr[$i] == $el) {
        unset($out[$i]);
    }
    else {
        $el = $out[$i];
    }
}

$out = array_values($out);

foreach ($out as $i) {
    echo $i."<br />";
}

Output:

1
2
...
6
7
8
...
10

Comments

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.