Skip to content
Tutorials Center
My learning

Topics

Lesson 113 of 147 ยท Advanced PHP

Internationalization and Localization

Build multilingual PHP apps - message catalogs, gettext-style keys, plural rules, locale-aware number, currency and date formatting, fallbacks and the intl extension.

A site that only speaks one language and formats numbers one way is easy to build and hard to grow. Internationalization (often shortened to i18n) means designing your code so it can be adapted to many languages and regions without rewriting it. Localization (l10n) is the adaptation itself: translating the text, choosing 1,234.50 or 1.234,50, writing the date as 03/04/2026 or 4. Mรคrz 2026.

The golden rule is simple: never build user-facing sentences by gluing strings together in code. Word order, plurals and punctuation differ between languages, so every sentence needs to be a complete, translatable unit with placeholders. This lesson builds a small translation system from scratch so you see every moving part, then shows how it maps onto PHP's gettext and intl extensions and what frameworks give you.

You need arrays, string formatting, multibyte strings and the basics of namespaces and classes.

Locales and message catalogs

A locale is a language plus optionally a region, written like en, en-US, de-DE or pt-BR. A message catalog maps a stable key (or the original English sentence) to the translation for one locale. In gettext the English text itself is the key; in most PHP frameworks you use a short key like cart.items. Either works; keys are easier to keep stable when the English wording changes.

flowchart TD
    A["Request: Accept-Language, URL prefix or user setting"] --> B["Pick locale: de-AT"]
    B --> C{"Key in de-AT catalog?"}
    C -- yes --> F["Use it"]
    C -- no --> D{"Key in de catalog?"}
    D -- yes --> F
    D -- no --> E{"Key in default (en)?"}
    E -- yes --> F
    E -- no --> G["Show the key itself and log it"]

A lookup walks from the most specific locale to the default, and finally reports the missing key.

Here is a minimal translator with placeholders and a fallback chain:

PHP A tiny translator with fallbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

de-AT overrides only the greeting and inherits logout from de. fr has no catalog at all, so it falls back to English. Named placeholders such as (rather than %s) let translators reorder words freely: a German sentence may need the name at the end where English puts it first.

Plurals are not just "s"

English has two forms (1 item, 2 items), so many developers write $n === 1 ? 'item' : 'items'. That breaks quickly:

  • French uses the singular for 0 and 1.
  • Russian and Polish have three or four forms depending on the last digits.
  • Arabic has six forms.
  • Japanese and Chinese have one form for every number.

The standard answer is the CLDR plural categories: zero, one, two, few, many, other. Each language defines a function from a number to a category, and each translation supplies one text per category it needs. Here is a plural-aware extension of our translator for a few languages:

PHP Plural categories per language

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the Russian row: 1 and 21 take the one form, 2 and 24 take few, and 5 and 11 take many. A translator needs to supply all forms the language needs, and your code must never assume two.

PHP's gettext extension solves this with ngettext('%d file', '%d files', $n) and a Plural-Forms: header in each .po file. The intl extension offers MessageFormatter with ICU syntax: {count, plural, one {# file} other {# files}}. Neither is available in our in-browser runner, so those snippets below are read-only.

Formatting numbers, currency and percentages

Even the digits you display depend on the reader: 1,234.5 in the US, 1.234,5 in Germany, 1 234,5 in France. PHP's built-in number_format() lets you choose the separators manually, so you can build a small formatter driven by per-locale settings:

PHP Locale-aware numbers and currency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real rules are more detailed (symbol placement, negative formats, grouping like 12,34,567 in India), which is why production code uses the ICU data through NumberFormatter from the intl extension:

PHP
$fmt = new NumberFormatter('de-DE', NumberFormatter::CURRENCY);
echo $fmt->formatCurrency(1234.5, 'EUR'); // 1.234,50 โ‚ฌ

$percent = new NumberFormatter('en-US', NumberFormatter::PERCENT);
echo $percent->format(0.256);             // 26%

Store money as integers (cents) or strings and only format at the edge, as described in Math Functions.

Dates and time zones

Store timestamps in UTC; convert to the user's time zone and format only when displaying. Without intl, the DateTimeImmutable class handles zones, and you map month and day names yourself:

PHP One moment, several presentations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The database value never changes; only the presentation does. With intl, IntlDateFormatter does the translation of month names and patterns for you:

PHP
$f = new IntlDateFormatter('de-DE', IntlDateFormatter::LONG, IntlDateFormatter::SHORT, 'Europe/Berlin');
echo $f->format($moment); // 4. Mรคrz 2026 um 16:30

Avoid strftime() and setlocale()-based formatting: strftime() is deprecated since PHP 8.1, and setlocale() depends on what the operating system has installed and is process-wide, which is dangerous in threaded or long-running servers.

gettext-style workflows

For large projects, translators work with .po files rather than PHP arrays. Each entry looks like this:

TEXT
#: src/Cart.php:42
msgid "You have %d item in your cart"
msgid_plural "You have %d items in your cart"
msgstr[0] "Sie haben %d Artikel im Warenkorb"
msgstr[1] "Sie haben %d Artikel im Warenkorb"

Tools like Poedit and platforms such as Weblate or Crowdin manage them. At runtime PHP can read compiled .mo files with the gettext extension, or a library parses .po files into the same kind of array we used above. Frameworks wrap all of this (Symfony Translation, Laravel's __() and trans_choice()), but the ideas are identical: catalogs, fallbacks, placeholders, plural categories.

Practical rules

  • Keep whole sentences. Never translate fragments and concatenate them.
  • Use named placeholders and let translators move them.
  • Pick the locale once per request (URL prefix, user profile, then Accept-Language), store it in one place, and pass it down rather than using globals.
  • Always set UTF-8 end to end, and use mb_* functions for case and length (Multibyte Strings).
  • Do not hard-code text direction. Arabic and Hebrew are right-to-left; set dir="rtl" on <html> from the locale.
  • Escape after translating. Translated text still goes through output escaping; never mark it safe just because translators wrote it.
  • Leave room. German text is often 30% longer than English; do not size buttons to the English label.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use a placeholder like instead of concatenating 'Hello, ' . $name?

    Word order differs between languages. A single sentence with named placeholders can be rearranged by the translator.
  2. 2. Which statement about plurals is correct?

    CLDR defines categories like one, few, many and other. Each language says which numbers use which category.
  3. 3. What should you store in the database for a point in time?

    UTC storage is unambiguous. Time zone conversion and localized formatting belong to the presentation layer.
  4. 4. A user requests de-AT, but the key exists only in the en catalog. What should a good lookup do?

    A fallback chain gives the best available text; logging missing keys tells you what to translate.

Summary

  • i18n prepares code for many locales; l10n supplies the translations and formats.
  • Use message catalogs with stable keys, named placeholders, and a fallback chain such as de-AT, de, default.
  • Plurals follow per-language CLDR categories; never hard-code "one or many".
  • Numbers, currencies and dates differ by locale; store raw values (integers, UTC) and format at the edge, with NumberFormatter/IntlDateFormatter when intl is available.
  • Gettext .po files and frameworks use the same ideas. Escape output after translation.

Next up: Sockets and Network Streams.