Jimi T
Jimi T

Reputation: 35

Can I use two sets of variables in one foreach loop?

Is is possible to construct one single foreach loop that loops through using two separate sets of variables?

Below is a simplified example of what I'm trying to do - except this example lists two separate loops whereas I would like to set them up in one single loop.

$Sites = @("https://www.google.com" , "https://duckduckgo.com")
$Site_names = @( "Google" , "DuckDuckGO")

foreach  ($element in $Sites) {
  Write-Host "`n`n"
  $element
  Write-Host "`n`n"
}

foreach ($name in $Site_names) {
  Write-Host "`n`n"
  $name
  Write-Host "`n`n"
}

There is other code to be used so the loop needs to be able to allow for multiple lines of code in the code block - so a single line solution if there is one isn't what I'm after. Also I didn't think using the pipeline would be workable (but I could certainly be wrong on that).

Two sets of variables: $Sites and $Site_names.

I would like one foreach loop that runs through and lists the site address and the site name with both values changing each time the loop is run.

Is this possible?

Upvotes: 1

Views: 193

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

If you have two arrays of the same size you can simply use a for loop like this:

for ($i=0; $i -lt $Sites.Count; $i++) {
  "{0}`t{1}" -f $Site_names[$i], $Sites[$i]
}

However, if the elements of your two arrays are correlated anyway, it would be better to use a hashtable instead:

$Sites = @{
  'Google'     = 'https://www.google.com'
  'DuckDuckGo' = 'https://duckduckgo.com'
}

foreach ($name in $Sites.Keys) {
  "{0}`t{1}" -f $name, $Sites[$name]
}

Upvotes: 1

Related Questions