1

I have a foreach loop that iterates over an Array and calls a function which also has another foreach loop inside with an incremental counter, however it doesn't seem to be working as expected?

Array contents:

| Username | Username2 |
|----------|-----------|
| p1       | p2        |
| p3       | p4        |

Code:

function insertIntoLunchJobs($arrayOfRows) {
    $counter = 1

    foreach ($i in $arrayOfRows) {
        $i
        $counter++
        $counter
    }
}

Output:


| Username | Username2 |
|----------|-----------|
| p1       | p2        |
| 2        |           |
| p3       | p4        |
| 2        |           |

Desired result:


| Username | Username2 |
|----------|-----------|
| p1       | p2        |
| 2        |           |
| p3       | p4        |
| 3        |           |

Any ideas?

TIA

2
  • You want to do a for loop. Commented Mar 19, 2021 at 2:43
  • Thanks @AbrahamZinala do you know how I can construct that? Commented Mar 19, 2021 at 2:45

1 Answer 1

2

I'm literally copy pasting your code. I don't see any errors here:

$arr=@'
Username,Username2
p1,p2
p3,p4
'@|ConvertFrom-Csv

function insertIntoLunchJobs($arrayOfRows) {
    $counter = 1

    foreach ($i in $arrayOfRows) {
        $i
        $counter++
        $counter
    }
}

insertIntoLunchJobs -arrayOfRows $arr

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate, I actually logically had an issue. Basically I did a foreach loop over $arr and then called the insertIntoLunchJobs function. Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.