Learn

Arrays are a data structure that holds a collection of items. Items can be of the same type or multiple types. We can think of arrays as a variable that can hold more than one value. Consider the example below:

$my_arr = 25, "Codecademy", 1, $False

my_arr is an array that holds the integer 25, the string Codecademy, the integer 1, and the boolean False – in that order. Referencing the variable will output each item one at a time.

PS > $my_arr 25 Codecademy 1 False

Separating items by commas is the simplest way to create an array, but it’s not the only way. Another way is to use the array subexpression operator @( ). Anything placed within the parentheses is treated as an item of the array. It can be anything from a single element to output from commands. The following examples best illustrate its usage.

$arr_1 = @($True, 5, (Get-Date).DateTime) # 3 elements $arr_2 = @( ) # Empty Array $arr_3 = @( # Multi-line Array "Uno" "Dos" "Tres" )

In the next exercise, we will go over different ways to access items in an array.

Instructions

1.

In the PowerShell terminal, create an array called fruits without using the array subexpression operator and add the following three items in the order provided as strings:

  1. apple
  2. orange
  3. tomato
2.

Using the single line version of the array subexpression operator to create an array called colors. In the order provided, add the following items as strings.

  1. cyan
  2. orange
  3. blue
3.

Print the colors array.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?