How can a loop be used to optimize the process of querying data in multiple languages in PHP?

When querying data in multiple languages in PHP, a loop can be used to iterate over an array of languages and dynamically construct the query based on the selected language. This approach eliminates the need to write multiple query statements for each language, making the code more efficient and maintainable.

$languages = ['en', 'fr', 'es']; // Array of languages
$queryResults = [];

foreach ($languages as $lang) {
    $query = "SELECT * FROM translations WHERE lang = '$lang'";
    $result = mysqli_query($connection, $query);
    
    while ($row = mysqli_fetch_assoc($result)) {
        $queryResults[$lang][] = $row;
    }
}

// Access query results for each language
print_r($queryResults);