1

I tried to describe a small 'list' of things, using arrays of arrays. An odd behaviour I observed:

function write-it-out([array] $arrays)
{
  foreach($a in $arrays)
  {
   write-host "items" $a[0] $a[1]
  }
}


$arrayOfArrays1 = @( 
  @("apple","orange"),
  @("monkey","bear")
)

$arrayOfArrays2 = @( 
  @("android","linux")
)


# it works 
write-it-out $arrayOfArrays1
# it wont
write-it-out $arrayOfArrays2

The first case outputs the expected two lines with the following content:

items apple orange
items monkey bear

But the second function call outputs not the expecteds

items android linux

but

items a n
items l i

Does somebody know why? And how to describe an array containing only one array inside, not more than one? So how to fix it? Thank guys in advance!

Zoltan Hernyak
  • 989
  • 1
  • 14
  • 35
  • 2
    The [accepted answer](https://stackoverflow.com/a/57391613/45375) to the linked question explains the problem well; as for why only the _first_ characters of the array elements are printed: if you index into a _string_, it is treated like an array of characters, and index `[0]` returns the first one; e.g.: `'foo'[0]` returns `'f'` – mklement0 Oct 16 '20 at 18:47

1 Answers1

1

I'm not exactly sure why, but when you declare $arrayOfArrays2, PowerShell is immediately unrolling the outer array.

> $arrayOfArrays2.Count
2

> $arrayOfArrays2[0]
android

In order to make it not do that, you can add an extra comma inside the outer array declaration like this.

> $arrayOfArrays2 = @(,@("android","linux"))

> $arrayOfArrays2.Count
1

> $arrayOfArrays2[0]
android
linux

> write-it-out $arrayOfArrays2
Items android linux
Ryan Bolger
  • 1,275
  • 8
  • 20
  • 2
    The workaround is effective, but note that there's no _outer array_ in `@( @("android","linux") )`, because `@()` doesn't _construct_ arrays, it _guarantees_ that something is an array - if it already is, it leaves it alone, loosely speaking - see the accepted answer to the linked duplicate and [this answer](https://stackoverflow.com/a/45091504/45375) – mklement0 Oct 16 '20 at 18:43