-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

3
  • 1
    Is that an array of arrays or an array of strings? Commented May 4, 2018 at 7:48
  • array values is string Commented May 4, 2018 at 7:49
  • 2
    use implode(), explode(), and array_unique(). Commented May 4, 2018 at 7:50

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.