What alternative approach can be used to avoid running the same query twice in PHP when needing to loop through the result set multiple times?

When needing to loop through a result set multiple times in PHP, running the same query again can be inefficient and resource-intensive. To avoid this, you can store the results in an array and then loop through the array as many times as needed. This way, the query is only executed once, and the results are reused without the need to query the database again.

// Execute the query and store the results in an array
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

// Loop through the result set multiple times without running the query again
foreach ($data as $row) {
    // Process the data
}

foreach ($data as $row) {
    // Process the data again
}