Using PHP Gettext Extension vs PHP Arrays in Multilingual Websites? Using PHP Gettext Extension vs PHP Arrays in Multilingual Websites? php php

Using PHP Gettext Extension vs PHP Arrays in Multilingual Websites?


I recommend using gettext, I am doing that in PHP for 5 years with good results.

First of all if you use echo _('my text to translate') and have no translation for it, you will see the original string in the output, which is good. Using arrays like echo $translation['were is my translation'] and there is none, you will just see nothing. but beware, using poedit and doing a echo _(''); is not a good idea, poedit uses the msgid "" for the project information which most likely you don't want to show your audience, so one must take care of not trying to translate empty strings :)

Also it's very fast and has some additional features for plurals and stuff, also poedit for example makes the life easier by having a translation db so you must not translate the same stuff over and over again, those you did already will be prefilled and marked as "check if it's right". Very comfortable.

theby middus mentioned downside that you have to compile the po file while you could easy overwrite a php-file when using arrays - well you just overwrite your mo file too, and if using poedit, it does the compiling after saving the file. So in fact you hit save and copy the file, sam as with editing a php-file.

But a real downside is, if you use mod_php. Be aware that with mod_php it is not threadsafe, though I never had any hard problems.

It's mostly just that you have to restart your apache when using mod_php or your gettext calls will fail (sometimes no translations returned, sometimes you end up with the beloved white page with no contents). But by using something like mod_itk (I believe cgi/fastcgi can do this to) you wont even have this problem no more.


Using GNU gettext you get support for placeholders like with printf and international plural forms. Placeholders order can be changed in translation or skipped.

Example from PHP documentation:

<?phpsetlocale(LC_ALL, 'cs_CZ');printf(ngettext("%d window", "%d windows", 1), 1); // gives "1 okno"printf(ngettext("%d window", "%d windows", 2), 2); // gives "2 okna"printf(ngettext("%d window", "%d windows", 5), 5); // gives "5 oke"?>

Another pro is that you can use standard tools for terminology management, translations memory and machine translation as pointed by @middus.

For shared environments there is a great php-gettext library from Danilo Segan.


The most obvious pro for using gettext() is of course that the source string is positioned where it belongs. I.e. it makes much more sense to write this

echo _("This is a string");

than

echo $lang['a_string'];

Not to mention that you have to craft a new variable placeholder for every possible translation. With gettext() the translation string itself acts as the index.