0

I have 2 dimension array. I would like to get each value of array. I tried this, but each array in $Name has all the array in $Date. But my expectation first item in $Name equal to first item in $Date. This is my expectation result:

A\11
B\12
C\13

$Name = @("A", "B", "C") #the size of this array not fixed
$Date = @("11", "12", "13") #the size of this array not fixed

foreach ($na in $Name)
{
     foreach ($dt in $Date)
     {
          $NameAndDate = "$na\$dt"
          Write-Host $NameAndDate
     }
}

but from the code above I got this result

A\11
A\12
A\13
B\11
B\12
B\13
C\11
C\12
C\13

Anyone can help, please. Thank you

6
  • Does this answer your question? Perform math operations with two equal length arrays Commented Feb 23, 2021 at 9:24
  • @iRon no, its not answer my question Commented Feb 23, 2021 at 9:33
  • are you trying to merge two 1-d arrays into one 2-d array? Commented Feb 23, 2021 at 9:54
  • 2
    @SBR - Your question does not make complete sense, Should "B\13" exist in your expected output? - If so you are not fully declaring what logic should determine this, if this is not the case I would advise a for loop: For ($i = 0; $i -lt $name.count; $i++){ ($Name[$i]) + "\" + ($Date[$i]) } Commented Feb 23, 2021 at 10:02
  • 1
    Please explain what you expect as an output. @jfmilner answer returns A\11 B\12 C\13 what I would guess you would actually expect (and what is described in the duplicate). But in your example script, you have A\11 B\12 B\13 C\13 in top, is that what you expect as an output? If yes, please explain where where the B\13 is coming from. Commented Feb 23, 2021 at 10:05

2 Answers 2

1

When combining two arrays, both having a non-fixed number of elements, you need to make sure you do not index beyond any of the arrays indices.

The easiest thing here is to use an indexed loop, where you set the maximum number of iterations to the minimum number of array items:

$Name = "A", "B", "C"    # the size of this array not fixed
$Date = "11", "12", "13" # the size of this array not fixed

# make sure you do not index beyond any of the array indices
$maxLoop = [math]::Min($Name.Count, $Date.Count)

for ($i = 0; $i -lt $maxLoop; $i++) {
    # output the combined values
    '{0}\{1}' -f $Name[$i], $Date[$i]
}

Output:

A\11
B\12
C\13
Sign up to request clarification or add additional context in comments.

Comments

1

Try this

$Name = @("A", "B", "C") #the size of this array not fixed
$Date = @("11", "12", "13") #the size of this array not fixed
foreach ($i in 0..($Name.Count -1)) {
    write-host ($Name[$i] + "\" + $Date[$i])
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.