Multidimensional arrays of any depth in PHP

Creating multidimensional arrays in PHP

There are times when you need to generate an array structure in advance of the data you want to store inside it. In most cases when I need this, I’ll create a few for loops to create my array structure, and insert my data as I build up my array. While this is fine, it can get a little messy for arrays of more than two or three dimensions, so a clean approach is to separate the array generation from the array content generation. You can always iterate over your array after you’ve generated it.

Recently, I needed the ability to create an array of any depth, so I wrote a function that would allow me to do so. PHP’s arrays are dynamic, but the built in array() function in PHP doesn’t allow you to specify a size when you create an array. However, because arrays in PHP are dynamic, it’s very easy to create dynamically sized arrays on the fly.

The code:

If we want to create a 3×3 array:

If you wanted to create a 3x3x3 array, you can use create2dArray() with the PHP built-in function array_fill():

If you wanted to create a 3x3x3x3 array, aka a 4-dimensional array:

Using a combination of the techniques above, you can create an array of any depth, and you can tailor the create2dArray() function to your specific multi-dimensional array-creating needs.

Multidimensional arrays can be a little tricky to get your head around at first, so if you’re having trouble visualising what your multidimensional array looks like, use this snippet:

Let’s go one step further. You might not even know what level of depth your array will need to be at run-time, so it would be great if you could dynamically determine what level of depth you want your array to be via user-input or some other method, and then generate your array based on those values.

Now, using both createDynamicArray() and create2dArray(), we can create an array of any depth dynamically;

Create a 4x4x3x3x2x2 array:

Create a 4x4x3x3x10 array:

Leave a Reply

Your email address will not be published. Required fields are marked *