How can PHP be used to dynamically switch between different language versions of text in a template?

To dynamically switch between different language versions of text in a template using PHP, you can store the translations in an array or a database and then use a session variable or a parameter in the URL to determine the language to display. You can then retrieve the appropriate translation based on the selected language and replace the text in the template accordingly.

<?php
// Define the translations for different languages
$translations = [
    'en' => [
        'welcome_message' => 'Welcome to our website!',
        // Add more translations here
    ],
    'fr' => [
        'welcome_message' => 'Bienvenue sur notre site web!',
        // Add more translations here
    ]
];

// Set the default language
$default_language = 'en';

// Get the selected language from session or URL parameter
$language = isset($_SESSION['language']) ? $_SESSION['language'] : $default_language;

// Function to get translated text
function translate($key, $lang) {
    global $translations;
    return isset($translations[$lang][$key]) ? $translations[$lang][$key] : '';
}

// Example usage in template
echo translate('welcome_message', $language);
?>