getButterfly Logo getButterfly code wrangling since 2005

A long time ago I wrote a small tutorial for multilingual web sites using PHP. That tutorial is a bit outdated and unoptimized. I recently had to turn a static localized CRM into a multilanguage one. The obvious solution, without relying on gettext functions was to use PHP arrays.

So, here we go:

First of all we need a configuration setting inside our script’s config.php file. For the sake of our example, we’ll add a manual variable change:

// language settings
$lng = ‘en’;

Next, our header file, dubbed header.php (could be head.php or top.php in your script) will contain these lines:


You now, obviously, have to create a languages directory and create a new file called en.php. This file will hold our array of words and expressions:

@Package: My Multilanguage Script
@Language: English (English)

$lang = array();

$lang[‘REGISTER’] = ‘Register’;
$lang[‘USERNAME’] = ‘Username’;
$lang[‘PASSWORD’] = ‘Password’;
$lang[‘LOGIN’] = ‘Log in’;
$lang[‘LOGOUT’] = ‘Log out’;
$lang[‘DASHBOARD’] = ‘Dashboard’;

Notice how I tried to keep the array index name as close to translation as possible. For example, you’ll have the string “Separate tags with commas” as $lang[‘SEPARATE_TAGS_COMMAS’]. It’s easier after a couple of months when you’ll make changes.

Also, try to keep consistent naming of your language files, such as fr.php, de.php, ru.php, cn.php.

Now, call in you script <?php echo $lang[‘REGISTER’];?>. It will display “Register”, just as you translated it in your language file.

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply