Share via

problem with arrays

John Powers 1 Reputation point
2022-11-21T16:06:22.863+00:00

Hi. I am having trouble working with an array of arrays. Here is a simplified demonstrator of what I am trying to do and how it goes wrong. Say I have an array of arrays. I can create it quite easily with the command:

PS C:\work> $array = ((10,11,12),(20,21,22))

This creates what I expect - an array of 2 elements, each element being an array. I can confirm this with:

PS C:\work> $array.count; $array | foreach {[string]$_}
2
10 11 12
20 21 22

However if I try to add another element to this array, it splits that down into its atomic parts, such as:

PS C:\work> $array += (30,31,32)

  • and I do not get an array of 3 elements, but the 3rd broken up to make 5 elements, thus:

PS C:\work> $array.count; $array | foreach {[string]$_}
5
10 11 12
20 21 22
30
31
32

It has broken up the last array. I have tried other syntaxes
$array += ((30,31,32)) # (2 brackets, like the create)
$array += array # (force a variable type ARRAY)
but they all do the same thing. What am I misssing?

Many thanks for your help. John

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

1 answer

Sort by: Most helpful
  1. Rich Matheisen 48,116 Reputation points
    2022-11-21T16:32:57.587+00:00

    Ahhh, this needs the magic comma!

    $array = ((10,11,12),(20,21,22))  
    $array += ,(30,31,32)  
    $array.count; $array | foreach {[string]$_}  
    

    When you add an array, it's flattened. So "(30,31,32) is added one element of the array at a time. By placing the comma ahead of the array you're introducing an empty element and $null isn't passed through the implied pipeline (i.e., the flattening process). That leaves the array (the 2nd element of the array) to be added as an array because the comma is an array operator.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.