Skip to content
PHP Logo

What are some common methods for handling translation tables in PHP applications?

When working with multilingual PHP applications, it is common to use translation tables to store key-value pairs for different languages. One common method for handling translation tables is to store them in arrays or database tables and use a function to retrieve the appropriate translation based on the current language setting.

php
// Example of handling translation tables in PHP using arrays

// Define translation arrays for different languages
$translations = [
    'en' => [
        'hello' => 'Hello',
        'goodbye' => 'Goodbye'
    ],
    'fr' => [
        'hello' => 'Bonjour',
        'goodbye' => 'Au revoir'
    ]
];

// Function to retrieve translation based on current language setting
function translate($key, $lang) {
    global $translations;
    
    if (isset($translations[$lang][$key])) {
        return $translations[$lang][$key];
    } else {
        return 'Translation not found';
    }
}

// Example usage
$currentLang = 'fr';
echo translate('hello', $currentLang); // Output: Bonjour
echo translate('goodbye', $currentLang); // Output: Au revoir