How to remove duplicate values from an array in PHP
In this tutorial, we will explain to you how to remove duplicate values from an array in PHP. there are many ways to remove duplicate values from an array in PHP. PHP provides array_unique() method for remove duplicate value in array. so you can see our following example.
Remove Duplicate Values From An Array In PHP
In this example, we are taking a simple array as an example and the array_unique() method helps to remove the duplicate value in an array. so you can see the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php $arr = array(1, 2, 2, 3, 4); $final_arr = array_unique($arr); echo "<pre>"; print_r($final_arr); echo "<pre/>"; //output Array ( [0] => 1 [1] => 2 [3] => 3 [4] => 4 ) ?> |
Remove duplicate values from associative array in PHP
In this example, we are taking an associative array as an example and the array_unique() method helps to remove the duplicate value in an array. here in this example car values are duplicates so the array_unique() method will remove the duplicate car value. so you can see the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php $arr=array("a"=>"apple","b"=>"bike","c"=>"car","d"=>"dog","f"=>"car"); $final_arr = array_unique($arr); echo "<pre>"; print_r($final_arr); echo "<pre/>"; //output Array ( [a] => apple [b] => bike [c] => car [d] => dog ) ?> |
Remove duplicate values from multidimensional array in php
In this example, we are taking a multidimensional array as an example and the array_unique() method helps to remove the duplicate value in an array. here found duplicate index 0 and 3. it will remove the 3 duplicate index. so you can see the below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php $data = array( 0 => array("id"=>"1", "name"=>"kuldip"), 1 => array("id"=>"2", "name"=>"ajay"), 2 => array("id"=>"3", "name"=>"sandip"), 3 => array("id"=>"1", "name"=>"kuldip"), ); echo "<pre>"; print_r(array_unique($data, SORT_REGULAR)); echo "<pre/>"; //output Array ( [0] => Array ( [id] => 1 [name] => kuldip ) [1] => Array ( [id] => 2 [name] => ajay ) [2] => Array ( [id] => 3 [name] => sandip ) ) ?> |
Read Also
Convert XML into Associative Array in PHP
How To Add Days To Current Date In Php