PHP in_array object comparing?

后端 未结 8 1161
终归单人心
终归单人心 2020-12-17 08:37

Can the in_array function compare objects?

For example, I have an array of objects and I want to add them distinctly to another array. Is it possible t

8条回答
  •  [愿得一人]
    2020-12-17 09:36

    You can use strict comparison:

    in_array($object, $array, TRUE);
    

    Usage example:

    $a = new stdClass();
    $a->x = 42;
    
    $b = new stdClass();
    $b->y = 42;
    
    $c = new stdClass();
    $c->x = 42;
    
    $array = array($a,$b);
    
    echo in_array($a, $array, true); // 1
    echo in_array($b, $array, true); // 1
    echo in_array($c, $array, true); //
    

提交回复
热议问题