Format List Items According to Locale in PHP 8.5

Format List Items According to Locale in PHP 8.5

The PHP Intl extension provides functions for locale-related operations, such as formatting, transliteration, character encoding conversion, and other related tasks. Since PHP 8.5, we can use the IntlListFormatter class to format list items into human-readable strings that follow locale-specific rules. It automatically manages connectors like 'and', 'or' and other locale-specific list formatting conventions.

When creating an IntlListFormatter object, the constructor accepts a $type parameter. The available options are:

  • IntlListFormatter::TYPE_AND - formats the list using 'and'. Example: A, B, and C (Default).
  • IntlListFormatter::TYPE_OR - formats the list using 'or'. Example: A, B, or C.
  • IntlListFormatter::TYPE_UNITS - formats the list as a compound unit, without using 'and' or 'or'. Example: A, B, C.

The third parameter of the IntlListFormatter constructor is $width, which determines how compact or expanded the list appears. The options are:

  • IntlListFormatter::WIDTH_WIDE - the standard formatting. Example: A, B, and C (Default).
  • IntlListFormatter::WIDTH_SHORT - attempts a shorter format. If the language offers a shorter equivalent for 'and'/'or', it will be used. Example: A, B, & C.
  • IntlListFormatter::WIDTH_NARROW - uses the most compact formatting available for the locale, often omitting words like 'and'. Example: A, B, C.

Not all locales provide distinct short or narrow forms; in some cases, the output will be identical if the locale does not differentiate them.

<?php

$formatter = new IntlListFormatter('en_US');
echo $formatter->format(['A', 'B', 'C']).PHP_EOL; // A, B, and C

$formatter = new IntlListFormatter('en_US', IntlListFormatter::TYPE_OR);
echo $formatter->format(['A', 'B', 'C']).PHP_EOL; // A, B, or C

$formatter = new IntlListFormatter('en_US', IntlListFormatter::TYPE_UNITS);
echo $formatter->format(['A', 'B', 'C']).PHP_EOL; // A, B, C

$formatter = new IntlListFormatter(
    'en_US',
    IntlListFormatter::TYPE_AND,
    IntlListFormatter::WIDTH_SHORT
);
echo $formatter->format(['A', 'B', 'C']).PHP_EOL; // A, B, & C

$formatter = new IntlListFormatter('de_DE');
echo $formatter->format(['A', 'B', 'C']).PHP_EOL; // A, B und C

Leave a Comment

Cancel reply

Your email address will not be published.