Arrays hold multiple data points, and loops are a great way to iterate over the data with repetitive actions. Just like the foreach method of arrays, the foreach loop is a way to loop through arrays to access and process each array element.

$array = 51,12,31,4,15 foreach ($element in $array) { if ($element % 2 -eq 0) { Write-Host $element "is" Even } else { Write-Host $element "is" Odd } }

The foreach keyword is used in the above example, followed by parentheses. Inside the parentheses, the expression $element in $array tells the loop to iterate through each element of $array and set the value of $element to the values in the array. The code output is:

51 is Odd 12 is Even 31 is Odd 4 is Even 15 is Odd

As shown above, in the first loop iteration, $element is assigned the first element in the array, 51. In each iteration to follow, $element is updated with the next $array value.



Inside FOREACH_Example.ps1 create a foreach loop that defines a loop variable $ingredient and iterates through the array $recipe.

Leave the body of the loop empty.


Inside the foreach loop body, use Write-Host to output each $ingredient. Feel free to use the following line of code:

Write-Host "My recipe includes" $ingredient

Just be sure to output $ingredient. Your loop should iterate the length of the array $recipe.

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?