27: Format Localized Number Ranges
Overview
Section titled “Overview”Format a temperature range for US English and French. ICU provides locale-specific spacing, punctuation, and units.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - The
intlextension with ICU 63 or later. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable intl-number-range.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/27-intl-number-range/intl-number-range.php<?php
declare(strict_types=1);
foreach (['en_US', 'fr_FR'] as $locale) { $formatter = IntlNumberRangeFormatter::createFromSkeleton( 'measure-unit/temperature-celsius precision-integer', $locale, IntlNumberRangeFormatter::COLLAPSE_UNIT, IntlNumberRangeFormatter::IDENTITY_FALLBACK_SINGLE_VALUE, ); printf("%s %s\n", $locale, $formatter->format(18, 22));}Expected Result
Section titled “Expected Result”en_US 18–22°Cfr_FR 18–22 °CWhy It Works
Section titled “Why It Works”The skeleton specifies the unit and precision. The collapse setting controls when a repeated unit can appear once. The identity fallback determines the rendering when the endpoints format to the same value. Output can vary with the ICU and CLDR data shipped by your system.
Exercise
Section titled “Exercise”Format both endpoints as 18. With IDENTITY_FALLBACK_SINGLE_VALUE the range should display a single temperature.
Wrap-up
Section titled “Wrap-up”Continue with Read and Write ZIP Archives in Memory.