Got multiple arrays of IDs. Wanted to compare and remove the ids after I compare it with the original array.
$origialArr = [4883,8438,8468,4001,8577];
$arr = [
[8438,8468,4001,8577],
[4883,8438,8468,4001,8577],
[4883,8468,4001,8577],
[4883,8438,8468,4001,8577],
[4883,8438,8468,4001,8577],
]
Numbers or Ids that are not in $arr should be removed from the $originalArr.
What I’ve tried so far, but not working and cannot get rid of 4883 and 8438:
// attempt 1
$arr1 = [];
foreach ($arr as $item) {
$arr1[] = array_intersect($origialArr, $item);
}
// attempt 2
$anotherArr = [];
foreach ($arr as $item) {
foreach ($item as $id) {
$anotherArr[] = array_filter($origialArr, function($origArr) use ($id) {
if ($id === $origArr) {
return $id;
}
});
}
}
Expected output:
[8468,4001,8577]
Any help would be appreciated. Thank you!
>Solution :
I think your first attempt was almost there. If you take a cumulative approach instead:
$arr1 = $origialArr;
foreach ($arr as $item) {
$arr1 = array_intersect($arr1, $item);
}
or, if you want to be really compact about it:
$arr1 = array_reduce($arr, 'array_intersect', $origialArr);
Produces $arr1 = [8468, 4001, 8577];