Check number of iterations in a foreach for even or odd


#1

I want to check if the amount of results in a foreach loop are even or odd. Here’s the basic structure of my loop:

    $sql="...query stuff...";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user_selection]);    
    
    foreach ($stmt as $row) {
    }

To test if odd, believe I have to test it with something like this:

if ($num % 2 != 0) {
...do stuff...
}

I’m looking for the most optimal way to do this. Would I need to add a counter into the loop, or is there another way to count the results/iterations? Or, will I have to use a different loop type to do this?


#2

after executing the query just retrieve all results with fetchAll() then you can do a simple check if count($items) % 2


#3

Perfect! Thanks again for your help.