I've an array like this:
$array = ['a', 'b,c,d', 'e', 'f,g'];
Now I need to split items containing comma (s) and get a unique array, like this:
$array = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
I've tried
foreach ($array as $item) {
$new[] = explode(',', $item);
}
and
$res = array_map(function($val) {
return explode(',', $val);
}, $array);
But what I get, in both cases, is an array of (4) arrays.
How can I accomplish the array that I need?
CodePudding user response:
A simple solution would be to first add all of the items together using implode()
with a ,
separator and then explode
the result...
print_r(explode(",", implode(",", $array)));
CodePudding user response:
TO Get Unique Array:
$array = ['a', 'a,b,c,d', 'e', 'f,g'];
print_r(array_unique(explode(",", implode(",", $array))));
CodePudding user response:
Try it:
$array = ['a', 'b,c,d', 'e', 'f,g'];
$newArray = [];
foreach ($array as $a) {
$newArray = array_merge($newArray , explode(',', $a));
}
print_r($newArray);