Check number of iterations in a foreach for even or odd

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?

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

Perfect! Thanks again for your help.

Sponsor our Newsletter | Privacy Policy | Terms of Service