php find duplicate values in associative array code example
Example 1: get duplicate value from array php
$arr = array(1, 4, 6, 1, 8, 9, 4, 6);
$unique = array_unique($arr);
$duplicates = array_diff_assoc($arr, $unique);
print_r($duplicates);
Array ( [3] => 1 [6] => 4 [7] => 6 )
Example 2: php get keys of duplicate values in array
<?php
$array = array('a', 'a', 'b', 'c', 'd');
$unique = array_unique($array);
$duplicates = array_diff_assoc($array, $unique);
$result = array_diff($unique, $duplicates);
$unique_keys = array_keys($result);
$duplicate_keys = array_keys(array_intersect($array, $duplicates));
Example 3: php check for duplicates in array
function has_dupes($array) {
$dupe_array = array();
foreach ($array as $val) {
if (++$dupe_array[$val] > 1) {
return true;
}
}
return false;
}
Example 4: 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>";