Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate Multi-Dimensional Array with Nested Foreach Statement

I think this might be a pretty simple question, but I haven't been able to figure it out yet. If I've got a 2-dimensional array like so:

int[,] array = new int[2,3] { {1, 2, 3}, {4, 5, 6} }; 

What's the best way to iterate through each dimension of the array with a nested foreach statement?

like image 630
Tyler Murry Avatar asked May 23 '10 20:05

Tyler Murry


People also ask

How do you loop through a multi dimensional array?

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.

Can we use foreach loop for multidimensional array in PHP?

You can simply use the foreach loop in combination with the for loop to access and retrieve all the keys, elements or values inside a multidimensional array in PHP.

Can you nest foreach loops?

The nesting operator: %:% An important feature of foreach is the %:% operator. I call this the nesting operator because it is used to create nested foreach loops. Like the %do% and %dopar% operators, it is a binary operator, but it operates on two foreach objects.


1 Answers

If you want to iterate over every item in the array as if it were a flattened array, you can just do:

foreach (int i in array) {     Console.Write(i); } 

which would print

123456

If you want to be able to know the x and y indexes as well, you'll need to do:

for (int x = 0; x < array.GetLength(0); x += 1) {     for (int y = 0; y < array.GetLength(1); y += 1) {         Console.Write(array[x, y]);     } } 

Alternatively you could use a jagged array instead (an array of arrays):

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} }; foreach (int[] subArray in array) {     foreach (int i in subArray) {         Console.Write(i);     } } 

or

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} }; for (int j = 0; j < array.Length; j += 1) {     for (int k = 0; k < array[j].Length; k += 1) {         Console.Write(array[j][k]);     } } 
like image 183
ICR Avatar answered Sep 21 '22 10:09

ICR