-2

I have some arrays that I would like to combine to one and only take the same once, here's my arrays:

["ar1"]
["ar2"]
["ar2"]
["ar3"]
["ar4","ar2","ar5"]
["ar6","ar1"]
["ar5","ar3","ar7"]
["ar8","ar9","ar7"]
["ar3"]

I want it to return:

ar1,ar2,ar3,ar4,ar5,ar6,ar7,ar8,ar9

Is there an easy way to do that in PHP?

Klaus
  • 399
  • 1
  • 5
  • 17
  • 5
    [`array_merge()`](http://php.net/manual/en/function.array-merge.php) and [`array_unique()`](http://php.net/manual/en/function.array-unique.php) are your friends. – axiac May 24 '18 at 11:18

1 Answers1

-1

This is how you can do it:

$input = [
  ["ar1"],
  ["ar2"],
  ["ar2"],
  ["ar3"],
  ["ar4","ar2","ar5"],
  ["ar6","ar1"],
  ["ar5","ar3","ar7"],
  ["ar8","ar9","ar7"],
  ["ar3"],
];

if ($input) {
  $merged = call_user_func_array('array_merge', $input);
  $unique = array_unique($merged);
  $final = array_values($unique);
} else {
  $final = [];
}

print_r($final);

Output would look like this:

Array
(
    [0] => ar1
    [1] => ar2
    [2] => ar3
    [3] => ar4
    [4] => ar5
    [5] => ar6
    [6] => ar7
    [7] => ar8
    [8] => ar9
)

Some notes re code:

$merged -- this basically merges all items in input arrays into single array. We need if to take care of trivial case when there are zero input arrays (array_merge will fail in this case).

$unique -- here we remove all duplicates.

$final -- but array_unique also messes with array keys (instead of 0, 1, 2 you can get anything like 5, 7, 12, i.e. non-consecutive indexes), so, we should tidy up keys. This is optional step, depending on your task you might skip it. Here is how output looks if you skip this step (look at keys):

Array
(
    [0] => ar1
    [1] => ar2
    [3] => ar3
    [4] => ar4
    [6] => ar5
    [7] => ar6
    [11] => ar7
    [12] => ar8
    [13] => ar9
)
alx
  • 2,314
  • 2
  • 18
  • 22