How can PHP be optimized to efficiently handle language switching without duplicating code across multiple pages?

To efficiently handle language switching in PHP without duplicating code across multiple pages, you can use a centralized language file that contains all the language translations. By including this file in your PHP scripts, you can easily switch between languages without duplicating code. This approach helps maintain code consistency and makes it easier to manage language translations.

// language.php

$lang = array(
    'hello' => 'Hello',
    'goodbye' => 'Goodbye',
    // Add more language translations here
);

// index.php

include 'language.php';

echo $lang['hello']; // Output: Hello
echo $lang['goodbye']; // Output: Goodbye