What are the advantages of using foreach loops over for loops when iterating through database query results in PHP?

When iterating through database query results in PHP, using foreach loops is often preferred over for loops because foreach loops are specifically designed for iterating over arrays and objects, which is typically the data structure of query results. This makes the code more readable and concise as you don't need to manually manage the iteration index. Additionally, foreach loops automatically handle any changes to the array or object during iteration, ensuring that all elements are processed.

// Using a foreach loop to iterate through database query results
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

while ($row = mysqli_fetch_assoc($result)) {
    foreach ($row as $key => $value) {
        // Process each row element
        echo $key . ": " . $value . "<br>";
    }
}