Reputation: 129
Scenario:
Inputs: Arrays of Designation & Scale of teachers
A1:
[designation] => Array
(
[0] => 24
[1] => 25
[2] => 26
[3] => 27
[4] => 24
[5] => 25
)
[grade_scale] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 1
[5] => 10
)
Now, there is a same designation being repeated twice in A1 array, that's fine because same designation with different grades in A2 can exist.
However, if there are 2 occurrences of same designation then their grades should be different.
In above scenario, Designation 24 and 25 are duplicates.
What I have tried so far:
$counts = array_count_values($a1);
$filtered = array_filter($a1, function ($value) use ($counts) {
return $counts[$value] > 1;
});
$filtered
array gives me index numbers of duplicates.
$filtered
(
[0] => 24
[1] => 25
[4] => 24
[5] => 25
)
I want to check whether the values at same indexes in A2 array are duplicate too. In this scenario, designation 24 is having same grades in A2 at same indexes.
Upvotes: 2
Views: 217
Reputation: 92854
to check whether the values at same indexes in A2 array are duplicate too
The solution using array_filter
, array_count_values
, array_intersect_key
, array_flip
and array_unique
functions:
$a1 = [0 => 24, 1 => 25, 2 => 26, 3 => 27, 4 => 24, 5 => 25];
$a2 = [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 1, 5 => 10];
// getting all duplicate designation values from $a1 array
$counts = array_filter(array_count_values($a1), function($v){ return $v > 1; });
$dup_designations = [];
// iterating through all duplicate 'designation' items from $a1 array
foreach ($counts as $k => $v) {
// obtaining respective items from $a2 array by key intersection
// with current designation items sequence
$grades = array_intersect_key($a2, array_flip(array_keys($a1, $k)));
// check if found duplicates within $a2 array have the same value
if (count(array_unique($grades)) != count($grades)) {
$dup_designations[] = $k;
}
}
print_r($dup_designations);
The output:
Array
(
[0] => 24
)
Upvotes: 2