Opposite of array_chunk

Code:

$array = [[4,39,110], [9,54,854,3312,66950], [3]];
$array = call_user_func_array('array_merge', $array);

print_r($array);

Result:

Array
(
    [0] => 4
    [1] => 39
    [2] => 110
    [3] => 9
    [4] => 54
    [5] => 854
    [6] => 3312
    [7] => 66950
    [8] => 3
)

While PHP doesn't have a built in method to flatten an array, you can achieve the same thing using array_reduce and array_merge. Like this:

$newArray = array_reduce($array, function ($carry, $item) {
    return array_merge($carry, $item);
}, []);

This should work as an inverse operation to array_chunk.


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.


The "..." operator which turns an array into an arguments list can come in very handy in this case (https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list).

The inverse of array_chunk() could be this:

array_merge(...$chunks);

Example:

print_r(array_merge(...[[0,1,2],[3,4,5]]));

Output:

Array
(
   [0] => 0
   [1] => 1
   [2] => 2
   [3] => 3
   [4] => 4
   [5] => 5
)

Tags:

Php

Arrays