Remove duplicate values from an array in PHP

array_unique() function can remove the duplicate elements or values from an array. It takes an input array and returns a new array without duplicate values.

$array = array("Samsung", "Apple", "Xiaomi", "Apple", "Huawei");
$result = array_unique($array);
print_r($result);
//output: Array ( [0] => Samsung [1] => Apple [2] => Xiaomi [4] => Huawei )

If an array has string keys instead of integer ones, the function will keep a key’s first appearance for all values and ignore the others.

$array = array(
	'color' => "Green",
	'weight' => "0.5kg",
	'length' => "100cm",
	"0.5kg",
	"Red",
	"0.5kg",
);
$result = array_unique($array);
print_r($result);
//output: Array ( [color] => Green [weight] => 0.5kg [length] => 100cm [1] => Red )

Leave a Comment

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

We care about your privacy and data security. Google serves cookies to analyse traffic and show ads on this site. By using this site you agree to these cookies being set. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close