Opposite of array_chunk

arrays, php

Solution

Lifted from the PHP documentation on `array_values`:

/** 
 * Flattens an array, or returns FALSE on fail. 
 */ 
function array_flatten($array) { 
  if (!is_array($array)) { 
    return FALSE; 
  } 
  $result = array(); 
  foreach ($array as $key => $value) { 
    if (is_array($value)) { 
      $result = array_merge($result, array_flatten($value)); 
    } 
    else { 
      $result[$key] = $value; 
    } 
  } 
  return $result; 
}

PHP has no native method to flatten an array .. so there you go.

Problem

`array_chunk` splits an array into multiple arrays using a chunk size to make the cuts. What if I have an array of arrays of values, and I just want one big array of values? I could use `array_merge`, but that would require me to enumerate all the sub-arrays, of which there may be a variable number. For now, my solution is: ``` foreach($input as $tmp) {foreach($tmp as $val) { ... }} ``` But that's kind of messy and only works because I want to use the values. What if I wanted to store the array somewhere? EDIT: The input is coming from a set of `<select multiple>` boxes, used to select items from multiple categories. Each item has a globally unique (among items) ID, so I just want to combine the input into a single array and run through it. The input might look like: ``` [[4,39,110],[9,54,854,3312,66950],[3]] ``` Expected output: ``` [4,39,110,9,54,854,3312,66950,3] ``` or: ``` [3,4,9,29,54,110,854,3312,66950] ```

Original source

Related problems