-4

I have an array that looks like below:

$var[] =   ^ array:4 [▼
      0 => array:1 [▼
        0 => "apple"
      ]
      1 => array:1 [▼
        0 => "apple"
        1 => "grape"
      ]
      2 => array:1 [▼
        0 => "orange"
      ]
      3 => array:1 [▼
        0 => "banana"
      ]
    ]

Is there a way to convert this array into comma separated list with unique values as below?

$var = "apple,grape,orange,banana"

I tried implode(', ',$var) but it's not working as expected. Any help pls?

Update: My sub-array may have more than 1 element. It's dynamic.

Rick
  • 1,392
  • 1
  • 21
  • 52

2 Answers2

1

This produces the results given the expected input. Basically array_column get's the first item from each item of the array (0 based). Then array_unique on that will simply get the values without duplicates.

$arr = [
    ['apple'],
    ['apple'],
    ['banana'],
    ['pie'],
];

print_r(array_unique(array_column($arr, 0)));

EDIT: since there might be more than one item in the inner arrays, there's no shame in doing a non one-liner solution:

$result = [];
foreach ($arr as $row) {
    foreach ($row as $item) {
        if (array_search($item, $result) === false) {
            $result[] = $item;
        }
    }
}
print_r($result);
IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • Thanks. But in some cases, my inner element has more than 1 element like:$arr = [ ['apple'], ['apple','orange'], ['banana'], ['pie'], ]; In that case how to change array_column to include all array elements? – Rick Aug 24 '22 at 23:50
  • I have edited the question to add a sample. Pls chec – Rick Aug 25 '22 at 00:07
0

There's also a one-liner solution:

$result= array_unique(call_user_func_array('array_merge', $arr));

cf. https://stackoverflow.com/a/14972714/13720553

schmauch
  • 630
  • 1
  • 7
  • 10