What is the best method to count and insert a row of advertisement in PHP when looping through query results?

When looping through query results in PHP, the best method to count and insert a row of advertisement is to keep track of the loop iteration using a counter variable. Once the counter reaches a certain threshold (e.g. every 3rd row), insert the advertisement row into the results array before continuing with the loop.

// Assuming $queryResults is the array of query results
$counter = 0;
$adRow = ['advertisement']; // Advertisement row data

foreach ($queryResults as $row) {
    // Insert advertisement row every 3rd iteration
    if ($counter % 3 == 0 && $counter != 0) {
        array_push($queryResults, $adRow);
    }
    
    // Process and display the current row
    // ...
    
    $counter++;
}

// Insert advertisement row at the end if necessary
if ($counter % 3 == 0 && $counter != 0) {
    array_push($queryResults, $adRow);
}