Home > other >  How to get unique value in multidimensional array in Laravel?
How to get unique value in multidimensional array in Laravel?

Time:07-26

I have the following multidimensional array.

  "PM" => array:6 [▼
    0 => "Zeb"
    1 => "Pen"
    2 => "Zeb"
    3 => "Eds"
    4 => "Fsa"
    5 => "Zeb"
  ]
  "OS" => array:3 [▼
    0 => "Min"
    1 => "Kep"
    2 => "Min"
  ]
  "IT" => array:8 [▶]
] 

And I would like to remove the duplicate values from the nested arrays. In this case, have only one value Zeb in PM and Min in OS. Please keep in mind that, I don't know in which array there are duplicates so I need a way to check all the nested arrays for duplicates. Thank you.

CodePudding user response:

$arr = [
            "PM" => ["Zeb", "Pen", "Zeb", "Eds", "Fsa", "Zeb"],
            "OS" => ["Min", "Kep", "Min"],
        ];

$cleanArray = collect($arr)->map(fn($subarr) => array_unique($subarr))->toArray();

will produce:

[
     "PM" => ["Zeb", "Pen", "Eds", "Fsa"],
     "OS" => ["Min", "Kep"]
]
  • Related