1

I have a array with some array values contains multiple values separated by comma as shown below.



    $a  =  array(
              '0' => 't1,t2',
              '1' => 't3',
              '2' => 't4,t5'
           );   

I need output in the following format.


   Array
    (
        [0] => t1
        [1] => t2
        [2] => t3
        [3] => t4
        [4] => t5
    )



This is how tried and getting the results. Is there any other alternative way without looping twice.


    $arr_output = array();

    foreach($a as $val)
    {
        $temp = explode(',', $val);
        foreach($temp as $v)
        {
            $arr_output[] = $v;
        }
    }

Thanks.

orangetime
  • 55
  • 1
  • 6

2 Answers2

1
$array = Array (
        "t1,t2",
        "t3",
        "t4,t5"
    );

$splitted = array_map (function ($a) {return explode (",", $a);}, $array);
$arr = array_reduce($splitted, function ($a, $b) {
     return array_merge($a, (array) $b);
}, []);    

print_r ($arr);

First of all, you split every string by coma. You get an array of arrays. To merge them, you call a merging function, such as the one in the example with array_reduce.

akond
  • 15,865
  • 4
  • 35
  • 55
1

First convert your old array in to string like,
$old_array = array ( "t1,t2", "t3", "t4,t5" );
to
$string = implode(",", $old_array);
Now
echo $string;
gives a string with coma separator now using this you get desired array

$new_array = explode(",", $string);

If you print this you will get

Array(
[0] => t1
[1] => t2
[2] => t3
[3] => t4
[4] => t5)
prudhvi259
  • 547
  • 2
  • 9
  • 31