Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removed a value in array comparing to multiple array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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];

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading