How can PHP arrays be efficiently utilized for language translations in a multilingual website?
To efficiently utilize PHP arrays for language translations in a multilingual website, you can create an associative array where the keys represent the language codes and the values are arrays containing the translations for each language. This allows for easy access to translations based on the selected language.
// Define translations for different languages
$translations = array(
'en' => array(
'welcome' => 'Welcome',
'hello' => 'Hello'
),
'fr' => array(
'welcome' => 'Bienvenue',
'hello' => 'Bonjour'
)
);
// Function to get translation based on language and key
function translate($lang, $key) {
global $translations;
if (isset($translations[$lang][$key])) {
return $translations[$lang][$key];
} else {
return 'Translation not found';
}
}
// Example usage
echo translate('en', 'hello'); // Output: Hello
echo translate('fr', 'welcome'); // Output: Bienvenue