-1

I have an array that looks like this

Array
    (
        [0] => 1,2,4
        [1] => 1
        [2] => 1,2
        [24] => 2
        [44] => 1,2,3,4,5
        [86] => 1,2,5
        [139] => 4
        [156] => 1,4
        [170] => 1,2,4,5
        [201] => 1,3
        [208] => 1,2,3
        [237] => 1,5
    )

Now i want to merge all values into one single array without the duplicates so the desired output should look like this

Array(
[0]=>1,2,3,4,5
)

Any help would be appreciated. Thanks

Elland
  • 117
  • 2
  • 13

2 Answers2

2

Short version:

$result = implode(',', array_unique(explode(',', implode(',', $array))));

Explanation:

First you need to join all array elements to one string using implode() and "," as divider.

This will have the effect that

Array
(
    [0] => 1,2,4
    [1] => 1
    [2] => 1,2
)

will be joined to a string that looks like

1,2,4,1,1,2

Then you explode the string by using explode() and "," which will split up all elements into a single array value

Array
(
    [0] => 1
    [1] => 2
    [2] => 4
    [3] => 1
    [4] => 1
    [5] => 2
)

Then you make the values of the array unique by using array_unique() which will give you an array like this:

Array
(
    [0] => 1
    [1] => 2
    [2] => 4
)

At the end you implode them again by using implode() and "," and here is your result as a string:

1,2,4
Bernhard
  • 1,852
  • 11
  • 19
0

Something like this should do it:

$output = [];
array_map(function ($numbers) use (&$output) {
    $output = array_merge($output, explode(",", $numbers));
}, $input);
$output = array_unique($output);
duncan3dc
  • 248
  • 1
  • 5