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.

Syntax:

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

/* Output
Array
(
    [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.

Cheers,
JENSon.

 

 

Leave a Reply

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