Home > other >  if there is duplicate values from an array delete all duplicates values
if there is duplicate values from an array delete all duplicates values

Time:03-20

My problem is I had two array that i merged together to make one, but when i merged them i saw there was duplicates values.

Anyone knows if there are duplicate values "delete" every values who contains the same value like :

$a=array("red", "green", "red", "blue");

Instead of this result with array_unique :

[0] => red
[1] => green
[3] => blue

have this result :

[1] => green
[3] => blue

CodePudding user response:

<?php
$a=array("red", "green", "red", "blue", "blue", "yellow");
$duplicates = [];
for ($i=0; $i<count($a)-1; $i  ) {
    for($j=$i 1; $j<count($a); $j  ) {
        if ($a[$i] === $a[$j]) {
            $duplicates[] = $i;
            $duplicates[] = $j;
        }
    }
}

foreach($duplicates as $index) {
    unset($a[$index]);
}

print_r($a);

Prints:

Array
(
    [1] => green
    [5] => yellow
)
  • Related