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?
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.
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.
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.
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]); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With