remove duplicates in associative array php code example
Example 1: php remove duplicates from array
<?php
$fruits_list = array('Orange', 'Apple', ' Banana', 'Cherry', ' Banana');
$result = array_unique($fruits_list);
print_r($result);
?>
Output:
Array ( [0] => Orange [1] => Apple [2] => Banana [3] => Cherry )
Example 2: filter duplicate associative array by value check in php
<?php
function unique_key($array,$keyname){
$new_array = array();
foreach($array as $key=>$value){
if(!isset($new_array[$value[$keyname]])){
$new_array[$value[$keyname]] = $value;
}
}
$new_array = array_values($new_array);
return $new_array;
}
$student_arr[] = array("name" => "Yogesh Singh","age"=>24);
$student_arr[] = array("name" => "Sonarika Bhadoria","age"=>24);
$student_arr[] = array("name" => "Anil Singh","age" => 23);
$student_arr[] = array("name" => "Mayank Patidar","age" => 25);
$student_arr[] = array("name" => "Anil Singh","age" => 19);
$student_unique_arr = unique_key($student_arr,'name');
echo "<pre>";
print_r($student_arr);
echo "</pre>";
echo "<b>Array after remove duplicate key</b>";
echo "<pre>";
print_r($student_unique_arr);
echo "</pre>";