Reputation: 29
I am still new to powershell, right now I study foreach
with break
, I understand the concept, but when it combined with additional variable and break
; it confuses me, here is the code:
$i=0
$varZ = (10,20,30,40)
foreach ($var in $varZ)
{
$i++
if ($var -eq 30)
{
break
}
}
Write-Host "30 was found in array position $i"
the result I get showing that variable $i
= 3, where $var
= 30
but what confuses me, as I understand $i
starts with 0 and there is an array $varZ
(10,20,30,40), as I understand when $i
= 0 $var
= 10, hence $i
= 3 $var
= 40? please correct me and help me understand this code
Upvotes: 0
Views: 171
Reputation: 357
You are incrementing $i before you do your conditional check; whereas; it should be done after your break statement. Although $i is set to 0 before you begin your loop, you immediately increment by 1 with your statement $i++; thus, when $var is 10, $i which was 0 not become 0+1=1 and so forth.
Upvotes: 2