PHP – Using Recursion to print out values in a multidimensional array.

This is a simple guide on how to print out the keys and values of a multidimensional array. For this particular example, we are going to assume that we do not know how many levels the array in question will possess. i.e. We will built a small script that will echo out all keys and values in a given array, regardless of how many levels it has.

For these examples, I will be using a process called recursion.

Simple Example

My first example will be pretty simple, just in case you are new to the world of PHP. For this, I will setup a basic array:

As you can see, I’ve created a multidimensional array with three levels. To print the values out, I will create a recursive function:

When we pass our array into the function above, it will loop through each value in the array. Inside the loop, we have an IF statement that will check to see if the current value is an array. IF the value in question is an array, we will pass it through to our function so that the same process can be repeated. IF the value is NOT an array, then it will print it out on to the page.

Try it out for yourself! Provide the recursive function above with some of your own custom arrays, just so you can see it in action! When it comes to programming, it is better to get your hands dirty.


What if we want to indent the values as we are printing them out? What if we want to see what level each value is on?

In this case, we add another parameter called $level, which will be incremented whenever we “take a step down”:

As you can see, $level has a default value of 1. Whenever we make a recursive call to our function, we will increment our $level variable by 1. We then use the str_repeat function, which will repeat the hyphen symbol a certain number of times. In this case, we are using our $level variable as the multiplier. i.e. If $level is equal to three, then three hyphen symbols will be printed out on to the page. A quick example of str_repeat in action:

As you can see, seven astericks characters have been printed out.

Printing out keys.

Printing out the keys of your array is trivial once you’ve figured out how to use recursion to print out its values.

As you can, we only needed to make one small change to the original function!

Facebook Comments