Answer the question
In order to leave comments, you need to log in
Is there a pattern for comparing two objects (PHP)?
For example, I want to compare two objects $apple1 and $apple2 and understand that they have differences:
$apple1 = new stdClass();
$apple1->color = red;
$apple1->size = 30;
//...
$apple2 = new stdClass();
$apple2->color = green;
$apple2->size = 30;
//..
Answer the question
In order to leave comments, you need to log in
If you just need to compare objects for equality, == will do the trick . If you need to get the differences between two objects, you can do this:
<?php
$a = (object) ['color' => 'red', 'foo' => 'bar'];
$b = (object) ['color' => 'green', 'foo' => 'bar'];
$diff = array_diff(get_object_vars($a), get_object_vars($b));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question