0

I have an array:

array:3 [▼
  0 => array:1 [▼
    "name" => "test#4"
  ]
  1 => array:1 [▼
    "name" => "C"
  ]
  2 => array:1 [▼
    "name" => "C"
  ]
]

I want to get only the unique values:

array:2 [▼
  0 => array:1 [▼
    "name" => "test#4"
  ]
  1 => array:1 [▼
    "name" => "C"
  ]
]

What PHP function should I use?

I use array_unique():

$group_array = [];
foreach ($private_group_devices as $i=>$group) {
    $group_array[$i]['name'] = $group['group_name'];
}
// dd($group_array);
dd(array_unique($group_array));

But I keep getting:

Array to string conversion

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
code-8
  • 54,650
  • 106
  • 352
  • 604

1 Answers1

2

You can pass the SORT_REGULAR flag into your array_unique call, as follows:

dd(array_unique($group_array, SORT_REGULAR));

By default, array_unique attempts to convert each item to a string (which doesn't quite work for arrays). Using SORT_REGULAR tells array_unique to compare items without converting their types.

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
  • Plus 1 for shorter than the one in the link. ;p – code-8 May 31 '16 at 19:13
  • Either solution would work, and it actually appears that my answer is the same as [the second-highest answer](http://stackoverflow.com/a/18373723/899126)! That being said, there is a caveat to using `array_unique` in this fashion; it is [not intended to work on multi dimensional arrays](http://php.net/manual/en/function.array-unique.php#refsect1-function.array-unique-notes). It works, but there may be some hairiness depending on the situation. – Chris Forrence Jun 01 '16 at 13:25