phparrayskeywhitelistarray-intersect

Remove elements from an associative array of objects using a flat, whitelist array


I need to filter an array of objects using a flat array of whitelisted values.

$objects = [
    3 => (object) ['tid' => 3],
    12 => (object) ['tid' => 12],
    9 => (object) ['tid' => 9],
];

$whitelist = [3, 4, 9, 11];

The whitelist doesn't contain 12, so that object should be removed.

Desired output:

[
    3 => (object) ['tid' => 3],
    9 => (object) ['tid' => 9],
]

Solution

  • After some clean up it was pretty clear what I needed, and this little bit sorts it out:

    foreach ($second_array as $foo) {
      if (!in_array($foo->tid, $first_array)) {
        unset($second_array[$foo->tid]);
      }
    }