Attila Naghi
Attila Naghi

Reputation: 2686

How to remove duplicates elements from array using php?

Hi this is my var_dump result. My problem is : If my array contains more than once the same "name"(in my case "Test2"), then remove one of them. In my case all of the information from [0] or [1]. Thx.

array(3) {
  [0]=>
  object(stdClass)#24 (14) {
    ["name"]=>
    string(19) "Test2"
    ["taskid"]=>
    string(5) "11526"
  }
  [1]=>
  object(stdClass)#25 (14) {
    ["name"]=>
    string(19) "Test2"
    ["taskid"]=>
    string(5) "11526"
  }
  [2]=>
  object(stdClass)#26 (14) {
    ["name"]=>
    string(19) "Test1"
    ["taskid"]=>
    string(5) "11525"
  }
}

I want this result :

array(3) {
      [0]=>
      object(stdClass)#24 (14) {
        ["name"]=>
        string(19) "Test2"
        ["taskid"]=>
        string(5) "11526"
      }
      [1]=>
      object(stdClass)#26 (14) {
        ["name"]=>
        string(19) "Test1"
        ["taskid"]=>
        string(5) "11525"
      }
    }

Upvotes: 0

Views: 45

Answers (2)

notnotundefined
notnotundefined

Reputation: 3751

You can use array_unique() function

Upvotes: 0

sergio
sergio

Reputation: 5260

In you example dublicates not an arrays but objects, so you need to combine like this array_map and array_unique:

$arrayResult = array_map("unserialize", array_unique(array_map("serialize", $inputArray)));

Or try

$arrayResult = array();
foreach ( $inputArray as $item ) {
    isset($arrayResult[$item->taskid]) or $arrayResult[$item->taskid] = $item;
}

var_dump($arrayResult); 

Upvotes: 1

Related Questions