Brian
Brian

Reputation: 294

Remove array that is duplicated one array away

I need to be able to remove any array that is one array from the previous one, if it is a duplicate.

$toarray = cccccce,cccccce,f5f5f5,f5f5f5,e8e8e8,cccccce,8e8e8c,ccccce,8e8e8f,fffffd

$color = $toarray;
$color = explode(",",$color);
$color = array_unique($color);
$color = implode(",", $color);

So I need it to look like this.

cccccce,f5f5f5,e8e8e8,cccccce,8e8e8c,ccccce,8e8e8f,fffffd

Upvotes: 0

Views: 47

Answers (2)

Sutandiono
Sutandiono

Reputation: 1750

You will need to go through the contents of array one by one and compare the value with the one next to it.

$toarray = "cccccce,cccccce,f5f5f5,f5f5f5,e8e8e8,cccccce,8e8e8c,ccccce,8e8e8f,fffffd";
$array = explode (',', $toarray);   // Convert the string to array

for ($i = 0, $len = count ($array); $i < $len - 1; $i++)
{
   // Compare against the value next to current item
   if ($array[$i] == $array[$i + 1])
   {
      unset ($array[$i]);
   }
}

print implode (', ', $array);
// Result: cccccce, f5f5f5, e8e8e8, cccccce, 8e8e8c, ccccce, 8e8e8f, fffffd

Upvotes: 1

shark
shark

Reputation: 325

$toarray = array("cccccce","cccccce","f5f5f5","f5f5f5","e8e8e8","cccccce","8e8e8c","ccccce","8e8e8f","fffffd");

$color = array_unique($toarray);

$result = implode(",", $color);
print_r($result);

result

cccccce,f5f5f5,e8e8e8,8e8e8c,ccccce,8e8e8f,fffffd

Upvotes: 1

Related Questions