Skip to content
PHP Logo

How can variables be dynamically inserted into PHP code for language localization?

To dynamically insert variables into PHP code for language localization, you can use placeholders in your language files and then replace them with the actual values at runtime using PHP's sprintf function. This allows you to easily switch between different languages without having to hardcode every possible variation of a sentence.

php
// Language file
$lang['welcome_message'] = 'Hello, %s! Welcome to our website.';

// PHP code
$userName = 'John';
$welcomeMessage = sprintf($lang['welcome_message'], $userName);
echo $welcomeMessage;