How can the implementation of a language switcher in PHP be optimized for scalability and maintenance on a large website with multiple languages?
Issue: To optimize the implementation of a language switcher in PHP for scalability and maintenance on a large website with multiple languages, we can use an array to store language codes and corresponding translations. This approach allows for easy addition of new languages and updates to translations without modifying the code.
// Language switcher implementation using an array for translations
$languages = [
'en' => [
'home' => 'Home',
'about' => 'About',
'contact' => 'Contact',
],
'fr' => [
'home' => 'Accueil',
'about' => 'À propos',
'contact' => 'Contact',
],
// Add more languages and translations as needed
];
$currentLanguage = 'en'; // Default language
if (isset($_GET['lang']) && array_key_exists($_GET['lang'], $languages)) {
$currentLanguage = $_GET['lang'];
}
function translate($key, $currentLanguage) {
global $languages;
if (array_key_exists($key, $languages[$currentLanguage])) {
return $languages[$currentLanguage][$key];
}
// Return the key itself if translation is not found
return $key;
}
// Usage example
echo translate('home', $currentLanguage); // Output: Home