0

I have two arrays filled with strings that are relational. I need to pull back the value from array 2 whilst iterating through array 1 in a foreach loop. How your i Achieve this? Here is my code:

$contracts = @("xytt"
               "deff"
               "mnoo")

$labels = @("London contract"
            "Dubai contract"
            "Glasgow contract")

foreach ($contract in $contracts){
#Do stuff with $contract
#Return label associated to contract object
}
9
  • 1
    How are the two arrays related? For example, when I look at 'xytt' in $contracts, how do I know which item in $labels it is related to? Unless you are stuck with this arrangement of data for some reason, I'd consider setting it up a different way. Commented Apr 27, 2018 at 12:56
  • Hi, They are squential. So [0]$Contract is associated to [0]$Label and so on. Commented Apr 27, 2018 at 12:58
  • 1
    Just as an FYI, for related data a Hash or Dictionary is generally a better data structure than related arrays. Commented Apr 27, 2018 at 13:38
  • How would i build these two arrays in to a hash table to query? Commented Apr 27, 2018 at 14:44
  • How do you generate the arrays in the first place? Commented Apr 27, 2018 at 15:03

2 Answers 2

2

You could use for loop and an index variable instead of foreach:

for ($i=0; $i -lt $contracts.Length; $i++) {
    $contract = $contracts[$i]
    $label = $labels[$i]
    Write-Host "$contract : $label"
}
Sign up to request clarification or add additional context in comments.

Comments

0

I agree with EBGreen, a hash table is more suited to the task.

Similarly to Janne Tuukkanen's script this one uses an index,
but based on a normal ForEach.

ForEach ($contract in $contracts){
    "{0} - {1}" -f $contract, $labels[$contracts.IndexOf($contract)]
}

Sample output:

xytt - London contract
deff - Dubai contract
mnoo - Glasgow contract

3 Comments

This makes a not necessarily valid assumption that all the entries in $contracts are unique.
@EBGreen You are right, a hash table would reveal that at an earlier point.
Not if you use $labels as the keys for the hash and they are unique.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.