PHP : Deleting Duplicates From An Array

By | March 13, 2013

Hey Folks,

PHP’s array_unique function allows you to remove duplicate values from an array.


$arr = array("a" => "Ford", "Mercedes", "b" => "BMW", "Lotus", "Ford", "Renault");
$result = array_unique($arr);
echo "<pre>";
echo "</pre>";

/* Output
    [a] => Ford
    [0] => Mercedes
    [b] => BMW
    [1] => Lotus
    [3] => Renault

Note : The keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.




Leave a Reply

Your email address will not be published. Required fields are marked *