4

i need to compare 2 objects to remove duplicates / find new enteries.

The objects are not identical, but they contain the same username key

Here is the layout

database object

array
  [0]db->username
  [0]db->something
  [1]db->username
  [1]db->something
  etc

other object

array
  [0]ob->username
  [0]ob->somethingElse
  [1]ob->username
  [1]ob->somethingElse
  etc

I imagine i can loop one array of objects, and compare the $db[$key]->username with an internal loop of the other object $ob[$key]->username but is there a cleaner way ?

I am looking to remove duplicates

1 Answers1

3

No, there is no cleaner way, you have to loop over the properties. If that are not StdClass objects, I would add a custom compare method to their class:

class Person {

   protected $id;
   protected $name;
   protected $age;

   /**
    * Compares two persons an returns true if their name
    * and age equals.
    */
   public function equals(Person $b) {
       if($b->name === $this->name && $b->age === $this->age) {
           return TRUE;
       }
       return FALSE;
   }
}

Then use it like this:

$personA = DB::getPersonById(1);
$personB = DB::getPersonById(2);

if($personA->equals($personB)) {
    echo "They are equal";
}

However, beside from this, why not just removing the duplicates using SQL or even better use unique keys in the DB to avoid duplicates at all?

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • What if the objects are identical, can i just do an == ? –  Dec 11 '13 at 23:28
  • No. `equals` has no special meaning (like in other programming languages) and operator overloading isn't supported by PHP. You need to call the method explicitly. – hek2mgl Dec 11 '13 at 23:28
  • There is one exception from that: The built-in `DateTime` class. You can compare `DateTime` objects using `<>==` operators. However, this is an exception hacked in C behind the scenes. Operator overloading has (unfortunately) never been exposed to userland. – hek2mgl Dec 11 '13 at 23:33
  • 1
    Actually, with php 5, the `==` operator does work with objects. `A == B` iff typeof A === typeof B and A has identical attributes to B – Sam Dufel Dec 11 '13 at 23:42
  • 1
    @hek2mgl - What? That works exactly as I said. If you run `new A(1) == new A(1)`, you get `true`, otherwise false. See http://www.php.net/manual/en/language.oop5.object-comparison.php as well. – Sam Dufel Dec 12 '13 at 17:48
  • @SamDufel Oh, I missed to reply to your comment. Yes what you say is true but in this question the objects don't have identical attributes just username duplicates should be removed. (I guess the id will differ in most scenarios when objects are retrieved from a database) – hek2mgl Apr 09 '14 at 12:10
  • 1
    That comment was pointed at @IvanRistic's `What if the objects are identical, can i just do an == ` - to which the answer is yes – Sam Dufel Apr 09 '14 at 16:49