( can't believe this hasn't been asked in SO yet... )
How can I remove duplicate values from an array in PHP?
( can't believe this hasn't been asked in SO yet... )
How can I remove duplicate values from an array in PHP?
Use array_unique().
Example:
$array = array(1, 2, 2, 3);
$array = array_unique($array); // Array is now (1, 2, 3)
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>";
}
Output of array_unique()
will have the same key of input array. That you should keep in mind.
explode(",", implode(",", array_unique(explode(",", $YOUR_ARRAY))));
This will take care of key associations and serialize the keys for the resulting new array :-)
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;