Whenever you need to remove duplicate values from simple array or multi-dimensional array in PHP and you can follow with given code to get unique values in array.
array_unique()
function are used to remove duplicate data from given array.
Now question is what value will be removed if there are two or more array values are same, in that scenario it will keep first appearance value in array and removed others.
There are two parameters which will be pass in array_unique()
, first specifying an array which is required and second is optioanl specifying sorting type.
Optional parameters sortingtype have possible values :
- SORT_STRING - Default
- SORT_NUMERIC
- SORT_REGULAR
- SORT_LOCALE_STRING
Remove duplicate values from an array in PHP
Have a look on given example to remove duplicate values from an array.
- <?php
- $a=array("a"=>"expertphp","b"=>"demo","c"=>"expertphp");
- echo "<pre>";
- print_r(array_unique($a));
- ?>
Output of array before removing duplicate values from a multi-dimensional array in PHP.
- Array
- (
- [a] => expertphp
- [b] => demo
- [c] => expertphp
- )
Output of array after removing duplicate values from an array in PHP.
- Array
- (
- [a] => expertphp
- [b] => demo
- )
Now you will know how to remove duplicate values from a multi-dimensional array.
Have a look on given example to remove duplicate values from a multi-dimensional array.
- <?php
- $input=Array(Array('ab','cd'),Array('ef','gh'),Array('ij','kl'),Array('ab','cd'));
- echo "<pre>";
- print_r($input);
- $input = array_map("unserialize", array_unique(array_map("serialize", $input)));
- print_r($input);
- ?>
Output of array before removing duplicate values from a multi-dimensional array in PHP.
- Array
- (
- [0] => Array
- (
- [0] => ab
- [1] => cd
- )
- [1] => Array
- (
- [0] => ef
- [1] => gh
- )
- [2] => Array
- (
- [0] => ij
- [1] => kl
- )
- [3] => Array
- (
- [0] => ab
- [1] => cd
- )
- )
Output of array after removing duplicate values from a multi-dimensional array in PHP.
- Array
- (
- [0] => Array
- (
- [0] => ab
- [1] => cd
- )
- [1] => Array
- (
- [0] => ef
- [1] => gh
- )
- [2] => Array
- (
- [0] => ij
- [1] => kl
- )
- )
Find the Duplicate values in array using PHP
- <?php
- $array=array("expertphp","demo","expertphp");
- $count_array = array_count_values($array);
- echo "<pre>";
- print_r($count_array);
- $results = array();
- foreach($count_array as $key=>$val){
- if($val == 1){
- $results[$key] = 'unique';
- }
- else{
- $results[$key] = 'duplicate';
- }
- }
- echo "<pre>";
- print_r($results);
- ?>
Output :
- Array
- (
- [expertphp] => 2
- [demo] => 1
- )
- Array
- (
- [expertphp] => duplicate
- [demo] => unique
- )