phparraysfilterdiffarray-difference

Remove objects from an array of objects if a property value is found in another flat array


I have 2 PHP arrays, a simple one:

array
  0 => int 5
  1 => int 6

and an array of objects:

array
  0 => 
    object(stdClass)[43]
      public 'id' => int 1
  1 => 
    object(stdClass)[46]
      public 'id' => int 3
  2 => 
    object(stdClass)[43]
      public 'id' => int 5
  3 => 
    object(stdClass)[46]
      public 'id' => int 6
  4 => 
    object(stdClass)[46]
      public 'id' => int 7

I'd like to make a diff of these 2 arrays to eliminate in the second those present in the first. In this example, I don't want the ids 5 and 6 in the second array.


Solution

  • Assuming $objects is your array of objects, and $values is your array of values to remove...

    You could use a foreach loop if you want to return objects:

    $values = array(5, 6);
    $objects = array(
        (object) array("id" => 1),
        (object) array("id" => 3),
        (object) array("id" => 5),
        (object) array("id" => 6),
        (object) array("id" => 7)
    );
    foreach($objects as $key => $object) {
        if(in_array($object->id,$values)) {
            unset($objects[$key]);
        }
    }
    

    Live demo (0.008 sec)

    If you want to use the diff function itself (that's possible but awkward, less readable and will just return an array of values) you can (as Baba suggested) return the id of the object inline:

    $values = array(5, 6);
    $objects = array(
        (object) array("id" => 1),
        (object) array("id" => 3),
        (object) array("id" => 5),
        (object) array("id" => 6),
        (object) array("id" => 7)
    );
    $diff = array_diff(array_map(function ($object) {
        return $object->id;
    }, $objects), $values);
    

    Live demo (0.008 sec)