0

What is the best way to merge a 2-dimensional array into a 1-dimensional array?

Source Array:

    $example = array(
        array(
            'red',
            'green'
        ),
        array(
            'blue',
            'brown'
        ),
        array(
            'yellow'
        )
    );

Required Output Array:

    $output = array(
        'red',
        'green',
        'blue',
        'brown',
        'yellow'
    );

Solution that works but I am not sure if it is the most efficient because the use of array_merge in a loop seems to be ugly:

    $output = array();
    foreach($example as $v) {
        array_merge($output , $v);
    }

Is there more efficient way of doing this?

steven
  • 4,821
  • 2
  • 25
  • 55

2 Answers2

3

One liner here is:

$output = call_user_func_array('array_merge', $example);
u_mulder
  • 53,091
  • 5
  • 44
  • 59
  • I'd add a comment to describe what this call does ... I'm bound to forget in 6 months time - something like `// flatten array` would save me puzzling later – Wee Zel Aug 31 '17 at 08:25
2

try this

$result = call_user_func_array('array_merge', $example);
print_r($result);

output will be

enter image description here


Edit As a text output

Array ( [0] => red [1] => green [2] => blue [3] => brown [4] => yellow )

Read more about call_user_func_array

Abdulla Nilam
  • 31,770
  • 15
  • 58
  • 79