Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

twoarmtom's avatar

Merge Plucked Arrays

I'm having trouble doing something I thought would be simple. I want to pluck the values of a column that stores an array, merge them into one array, and remove any duplicate values.

Here are my plucked values (I'm using Laravel v. 5.6):

$plucked_values = $all_cases->pluck('area_codes');

// returns this  

[["A1","A3","A5"],["A3","A7","A9"],["A1","A3","A8","A9","A10"]];

I've gotten close with str_replace and implode/exploding values, but I still end up with some duplicates. There must be a simple way to do combine them all and remove the duplicates.

Any suggestions?

0 likes
3 replies
Nakov's avatar
Nakov
Best Answer
Level 73

Here is my try.. I believe pluck() already returns a collection, but if it does not, here it is:

$array = collect([["A1","A3","A5"],["A3","A7","A9"],["A1","A3","A8","A9","A10"]]);

$result = $array->flatten()->unique();

dd($result);
Sinnbeck's avatar
$final = [];
foreach ($plucked_values as $values) {
   $final = array_unique (array_merge ($final, $values)) ;
}
twoarmtom's avatar

@nakov Perfect. Thank you! (it does return as a collection, I also added ->sort()->values() to extract only the values)

Please or to participate in this conversation.