Yes, you can use recursion . Here is an example of the output of all array elements:
function printAll($a) { if (!is_array($a)) { echo $a, ' '; return; } foreach($a as $v) { printAll($v); } } $array = array('hello', array('world', '!', array('whats'), 'up'), array('?')); printAll($array);
What you should always remember when doing a recursion is that you need a base case where you will no longer go deep.
I like to check the base case before continuing the function. This is a common idiom, but it is not necessary. You can also check the foreach just as well if you need to output or make a recursive call, but I often find it harder to maintain this path for this.
The "distance" between your current input and the base register is called an option and is an integer. Variant must be strictly reduced in all recursive calls. A variation in the previous example is the depth of $a . If you do not think about this option, you run the risk of getting endless recursions, and in the end the script will die because of. It is not uncommon to accurately document that this option is in a comment before recursive functions.
Emil VikstrΓΆm
source share