views:

3121

answers:

5

( can't believe this hasn't been asked in SO yet... )

How can I remove duplicate values from an array in PHP?

+17  A: 

Use array_unique().

Example:

$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
yjerem
Thanks, just what I was looking for :)
ThinkingInBits
@Ian - `Note that array_unique() is not intended to work on multi dimensional arrays.`
Peter Ajtai
A: 

I have done this without using any function.

$arr = array("1", "2", "3", "4", "5", "4", "2", "1");

$len = count($arr);
for ($i = 0; $i < $len; $i++) {
  $temp = $arr[$i];
  $j = $i;
  for ($k = 0; $k < $len; $k++) {
    if ($k != $j) {
      if ($temp == $arr[$k]) {
        echo $temp."<br>";
        $arr[$k]=" ";
      }
    }
  }
}

for ($i = 0; $i < $len; $i++) {
  echo $arr[$i] . " <br><br>";
}
Ashishdmc4
A: 

Output of array_unique() will have the same key of input array. That you should keep in mind.

Sunny
A: 

explode(",", implode(",", array_unique(explode(",", $YOUR_ARRAY))));

This will take care of key associations and serialize the keys for the resulting new array :-)

Deb
What would be the effect of `explode("," $YOUR_ARRAY)` when `$YOUR_ARRAY` is `array("1", "2", "3")`?
kiamlaluno
A: 

If you're able to control the creation of the array, you can use an associative array with the key = the value. That way, if you get duplicates, they just overwrite themselves.

$array["{$val}"] = $val;
Sam Dufel