What are some best practices for optimizing PHP code when working with query results to avoid duplicate outputs?

When working with query results in PHP, one common issue is duplicate outputs due to iterating over the results more than once. To avoid this, one solution is to store the results in a variable and then loop through that variable to display the data only once. This can help optimize the code and prevent duplicate outputs.

// Store query results in a variable
$query_results = $stmt->fetchAll();

// Loop through the results variable to display data
foreach ($query_results as $result) {
    // Output data here
    echo $result['column_name'] . "<br>";
}