How can I remove duplicates in an object array in PHP?

I have an object like this:

class FanStruct{
    public $date; 
    public $userid;

    function __construct($date, $id){
        $this->date = $date;
        $this->userid = $id;
    }
}

I have maximum of 30 of them in an array, and they are sorted by $userid.

What is the best way to go though the array, and remove duplicate objects based on $userid (ignoring $date)?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Here’s a simple test that at least should get you started. Your __toString method might need to be more elaborate to generate uniqueness for your instances of FanStruct

<?php

class FanStruct{
    public $date;
    public $userid;

    function __construct($date, $id){
        $this->date = $date;
        $this->userid = $id;
    }

    public function __toString()
    {
      return $this->date . $this->userid;
    }
}

$test = array(
  new FanStruct( 'today', 1 )
  ,new FanStruct( 'today', 1 )
  ,new FanStruct( 'tomorrow', 1 )
);

print_r( array_unique( $test ) );

?>

Solution 2

$temp = array($fans[$x]);
for(var $x=1;$x<sizeof($fans);$x++) {
  if ($fans[$x]->userid != $fans[$x]->userid)
     $temp[] = $fans[$x];
}

Requires a temporary variable, but works.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply