Thanks to the relatively new Number helper, ordinal numbers (like 1st, 2nd, 3rd, etc.) are now easy to output in Laravel. Let's take a look!
Pretty simply, use the new Number
helper and the ordinal
method. Here's an example:
dd("You're ranked " . Number::ordinal(1));
This will output:
You're ranked 1st
Of course, this works the same with any number — just pass it into ordinal
, and Laravel will do the rest.
Even more recently, you can now spell ordinal numbers with the Number
helper.
Instead of 1st, we can output first. To do this, use the spellOrdinal
method:
dd(Number::spellOrdinal(2)); // second
dd(Number::spellOrdinal(50)); // fiftieth
This is useful, of course, if you need a text-based representation of an ordinal number.
At first glance, it may seem that there's a ton of custom functionality behind these methods.
However, PHP already has this functionality built-in. Laravel is utilising these methods to make it more convenient and cleaner.
Here's what the ordinal
method looks like behind the scenes:
public static function ordinal(int|float $number, ?string $locale = null)
{
static::ensureIntlExtensionIsInstalled();
$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::ORDINAL);
return $formatter->format($number);
}
So, the Number
helper is simply using the built-in PHP NumberFormatter
class, taking in the locale (which you can specify) and formatting the number.
I'm sure you'll agree that using the Number
helper for ordinal methods is a lot cleaner than the NumberFormatter
method!