Jump to content

How do you remove the duplicate values in an array in this particular situation?


BMAN99

Recommended Posts

Hey guys,

 

I understand how to remove the duplicate values in an array using the "array_unique" function. But what if I want to remove only the duplicate values that occur "side by side"?

 

For example, if this is my array...

 

$array = array( 0 => 'Red', 1 => 'Blue', 2 => 'Blue', 3 => 'Green' );

 

... then one of the "Blue" values should be removed.

 

But if my array looks like this instead...

 

$array = array( 0 => 'Red', 1 => 'Blue', 2 => 'Green', 3 => 'Blue' );

 

... then I do not want any values removed, because the duplicate values do not occur next to each other in that scenario.

 

So, anyone know of a simple way to do this? FYI, I will not know the size of the array or its values in advance.

 

Thanks!

 

 

Link to comment
Share on other sites

One more from me.

http://php.net/manual/en/function.next.php

$transport = array('foot','foot','bike', 'car', 'plane','bike','bike','bike','car','foot');
$i = 0;
while($i < count($transport)){
if($transport[$i] == next($transport))
     unset ($transport[$i]);
$i++;
}
echo '<pre>'.print_r($transport, true).'</pre>';

PS. I think, Brand's solution runs faster than mine, but....any way  ;)

Link to comment
Share on other sites

One more from me.

http://php.net/manual/en/function.next.php

$transport = array('foot','foot','bike', 'car', 'plane','bike','bike','bike','car','foot');
$i = 0;
while($i < count($transport)){
if($transport[$i] == next($transport))
     unset ($transport[$i]);
$i++;
}
echo '<pre>'.print_r($transport, true).'</pre>';

PS. I think, Brand's solution runs faster than mine, but....any way  ;)

 

Always nice to have options. Thanks!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.