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.

4
  • post your code as well what you have tried? Commented Mar 9, 2017 at 5:52
  • @orangetime No need to use loops here, you can get desired output by using predefined php array functions. check my answer below. Commented Mar 9, 2017 at 6:25
  • @prudhvi259, Thank you very much. Your solution is very simple. Commented Mar 9, 2017 at 6:45
  • Earlier question which asks for more processing than needed for this task. Isolate comma-separated values, remove duplicates and empty values, then sort Commented Sep 19, 2022 at 4:07

2 Answers 2

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

Comments

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.

1 Comment

This is way too much processing. explode(',', implode(',', $array)) is all that is needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.