The function here flatterns an entire array and was not the behaviour I expected from a function of this name.

I expected the function to flattern every sub array so that all the values were aligned and it would return an array with the same dimensions as the imput array, but as per array_values() adjusting the keys rater than removing them.

Indeed you can, and that's what's so great about it. I have, for instance, a function that returns the results of a database query as an array. I want to keep the order that the entries were returned in, but at the same time I want to be able to access them _either_ by the position _or_ by some other index (such as some sort of ID in the database, gotten from elsewhere). In this case, I can make the function return an array from id to [array of values], and by a simple call to array_values() this is transformed into an array indexed from 0 to count()-1. Useful.

A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

Note that in a multidimensional array, each element may be identified by a _sequence_ of keys, i.e. the keys that lead towards that element. Thus "preserving keys" may have different interpretations. Ivan's function for example creates a two-dimensional array preserving the last two keys. Other functions below create a one-dimensional array preserving the last key. For completeness, I will add a function that merges the key sequence by a given separator and a function that preserves the last n keys, where n is arbitrary.

<?php/* * Flattening a multi-dimensional array into a * single-dimensional one. The resulting keys are a * string-separated list of the original keys: * * a[x][y][z] becomes a[implode(sep, array(x,y,z))] */

@Yassin Ezbakhe <yassin88 at gmail dot com>When we have to flatten multidimensional array of strings or numbers this method could be much faster.Inconvenience of this method is, that its speed depends on size of strings/numbers, which array contains - bigger strings, lower efficiency.Conclusion: Use this method for small amount of data in arrays (less than 500B per element in my case) which have many dimensions, in other case, use Yassin Ezbakhe method.