So far, if I have to loop through a multidimensional array, I use a foreach loop for each dimension. Show e.g for two dimensions
What do I do when I don't know the depth of the array? ie the depth is variable. The only thing I can think of is to code a whole stack of loops and to break the loop if the next value is not an array.This seems a little silly. Is there a better way? asked Jun 7, 2012 at 9:19
Yes, you can use recursion. Here's an example where you output all the elements in an array:
What you should always remember when doing recursion is that you need a base case where you won't go any deeper. I like to check for the base case before continuing the function. That's a common idiom, but is not strictly necessary. You can just as well check in the The "distance" between your current input and the base case is called a
variant and is an integer. The variant should be strictly decreasing in every recursive call. The variant in the previous example is answered Jun 7, 2012 at 9:28
Emil VikströmEmil Vikström 88.5k15 gold badges134 silver badges170 bronze badges 3 You can do the below function for loop-through-a-multidimensional-array-without-knowing-its-depth
by using above function, it will go through each of the multi dimensional array, below is the sample array you could pass to loop function :
answered Dec 12, 2018 at 4:46
Bathulah MahirBathulah Mahir 1,0912 gold badges15 silver badges23 bronze badges You can use recursion for this problem: Here is one example
It will use recursion to loop through array It will print like
answered Jun 7, 2012 at 9:28
Simple function inside
Another one showing
answered Jan 24, 2018 at 21:35
AbraCadaverAbraCadaver 77.5k7 gold badges62 silver badges84 bronze badges 1 Based on previous recursion examples, here is a function that keeps an array of the path of keys a value is under, in case you need to know how you got there:
answered Jan 1, 2019 at 19:25
HenryHenry 1,3441 gold badge14 silver badges23 bronze badges How do you loop through a multidimensional array in PHP?Looping through multidimensional arrays
Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.
How do you loop through an infinite nested array?“how to loop thru a nested array” Code Answer. let chunked = [[1,2,3], [4,5,6], [7,8,9]]; . for(let i = 0; i < chunked. length; i++) { ... . for(let j = 0; j < chunked[i]. length; j++) { ... . console. log(chunked[i][j]); }. What is recursive count in PHP?value. An array or Countable object. mode. If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.
|