Search code examples
powershellscriptingjagged-arrays

Iterate through jagged array


I'm learning Powershell Scripting and right now I'm trying to iterate through an array consisting of 2 value arrays while only printing out the first value.

For example, take the below array;

$array = (("fizz", "buzz"),
          ("foo", "bar"))

I would like to be able to print out the first values, so fizz and buzz.

Right now, I have the following code;

Foreach ($a in $array)
{
    Write-Host $a[0]
}

What I should be getting is fizz, but instead I'm getting fizz buzz [0]

Thanks


Solution

  • You need to think of the multidimensional array as a table with rows and columns like so:

    enter image description here

    so in your example where you want to get the first two columns in the first row, what you want is

    $array[0][0]
    $array[0][1]
    

    You can check this by running:

    Write-Host $array[0][0]
    Write-Host $array[0][1]
    

    What you are doing is iterating through each row and printing out column 0 for each row.

    Foreach ($a in $array)
    {
        Write-Host $a[0]
    }
    

    This is saying foreach row in $array print out column 0. To get your code working as expected you would need to change $array to $array[0]:

    Foreach ($a in $array[0])
    {
        Write-Host $a
    }
    

    This will give you the expected results and reads as foreach column in row 0 print column. The loop is however unnecessary as you can get the same result by simply using:

    Write-Host $array[0]
    

    Which just prints out the entire row.