How to "flatten" a multi-dimensional array to simple one in PHP?

how to s
how to b
how to get
how to draw
how to cook
how to make
how to r
wikihow search

It's probably beginner question but I'm going through documentation for longer time already and I can't find any solution. I thought I could use implode for each dimension and then put those strings back together with str_split to make new simple array. However I never know if the join pattern isn't also in values and so after doing str_split my original values could break.

Is there something like combine($array1, $array2) for arrays inside of multi-dimensional array?

Use array_walk_recursive

<?php

$aNonFlat = array(
    1,
    2,
    array(
        3,
        4,
        5,
        array(
            6,
            7
        ),
        8,
        9,
    ),
    10,
    11
);

$objTmp = (object) array('aFlat' => array());

array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);

var_dump($objTmp->aFlat);

/*
array(11) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
  [6]=>
  int(7)
  [7]=>
  int(8)
  [8]=>
  int(9)
  [9]=>
  int(10)
  [10]=>
  int(11)
}
*/

?>

Tested with PHP 5.5.9-1ubuntu4.24 (cli) (built: Mar 16 2018 12:32:06)

How-to, How To - Tips, Tricks and Hacks for Doing Everything Better | Lifehacker. How To is your one-stop channel for navigating the rough patches in life. From relationships to finances, here is where you’ll find simple, practical help from those who have been there. Show less

$array  = your array

$result = call_user_func_array('array_merge', $array);

echo "<pre>";
print_r($result);

REF: http://php.net/manual/en/function.call-user-func-array.php

Here is another solution (works with multi-dimensional array) :

function array_flatten($array) {

   $return = array();
   foreach ($array as $key => $value) {
       if (is_array($value)){ $return = array_merge($return, array_flatten($value));}
       else {$return[$key] = $value;}
   }
   return $return;

}

$array  = Your array

$result = array_flatten($array);

echo "<pre>";
print_r($result);

How To, Hey guys! Welcome back to another video. Make sure you subscribe and turn your notifications on right away so you don't miss a upload from me. Hope you  How-to definition is - giving practical instruction and advice (as on a craft). How to use how-to in a sentence.

This is a one line, SUPER easy to use:

$result = array();
array_walk_recursive($original_array,function($v) use (&$result){ $result[] = $v; });

It is very easy to understand, inside the anonymous function/closure. $v is the value of your $original_array.

How to - How to, Get more from your technology and gadgets with TechRadar's expert tips, tricks, hacks and advice. Learn how to do just about everything at eHow. Find expert advice along with How To videos and articles, including instructions on how to make, cook, grow, or do almost anything.

// $array = your multidimensional array

$flat_array = array();

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $k=>$v){

$flat_array[$k] = $v;

}

Also documented: http://www.phpro.org/examples/Flatten-Array.html

Technology how to guides, tips and tricks, Smart tips on how to make the most of all the tech in your life, from phones and smart home gadgets to internet safety. iPhone · Android. A how-to is an informal and often short video or text describing how to accomplish a specific task. A how-to is usually meant to help non-experts and consequently may leave out details that are important only to experts.

If you specifically have an array of arrays that doesn't go further than one level deep (a use case I find common) you can get away with array_merge and the splat operator.

<?php

$notFlat = [[1,2],[3,4]];
$flat = array_merge(...$notFlat);
var_dump($flat);

Output:

array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
}

The splat operator effectively changes the array of arrays to a list of arrays as arguments for array_merge.

How To, how-to. noun. Definition of how-to (Entry 2 of 2). : a practical method or instruction the how-tos of balancing a checkbook also : something (such as a book) that  Learn how to do (almost) anything at HowToDoThings! Explore instructive how-to articles and videos – make things, solve problems, be happy!

How-to, The Best Tech Newsletter Anywhere. Join 250,000 subscribers and get a daily digest of news, geek trivia, and our feature articles. Skip to content  The Woman Who Sang the Viral 'Lose Yo Job' Song Is Getting the Recognition—and Coins—She Deserves

How-To Geek, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  Find DIY projects and craft ideas perfect for inside or outside your home that can be done in a weekend or on a budget with step-by-step instructions at DIYNetwork.com.

W3Schools How TO, Ready to give up smoking? These tips will help you kick the habit for good. Today I show you how to make the best homemade mashed potato. Mashed potatoes are incredibly delicious! This recipe will show you how to make restaurant quality mash in the comfort of your own home.

Comments
  • Please check this link for solution : stackoverflow.com/questions/14951811/…
  • Another good reference question with perhaps better answers: How to Flatten a Multidimensional Array?
  • Does anyone know why this doesn't work unless I use the (depreciated) call-time pass by reference. i.e. array_walk_recursive($array, create_function('&$v, $k, &$t', '$t[] = $v;'), &$flattened); The function definition is correctly defined as pass by reference. but doesn't work unless I pass by reference during call-time.
  • @jskilski Objects ($objTmp in this example) are passed by reference automatically; arrays are not. Try using an anonymous function (php.net/manual/en/functions.anonymous.php) instead of create_function.
  • this doesnt work in php 5.3.3 due to a bug in array_walk_recursive - bugs.php.net/bug.php?id=52719
  • @crazyphoton The kink says also This bug has been fixed in SVN.
  • Why does this answer mention using array_values()? I can't see any use of that function involved in the answer at all.
  • This answer is much faster than the accepted answer.
  • Since php5.3 you can now use the splat operator: $result = array_merge(...$array); php.net/manual/en/…
  • Your first answer doesn't work with a multi-dimensional array. 3v4l.org/tY8vD
  • This is the only one that worked for me in a two level array.