Display numbers with ordinal suffix in PHP

ordinal suffix php

Display numbers with ordinal suffix in PHP

How to display numbers with Ordinal suffix like 1st, 2nd,3rd,etc ?

Ordinal numbers shows the order of elements in a set.  In other words they show rank or position.  “First” and “second” are both ordinal numbers but they do not say anything about the distance between first and second.

Ordinal numbers may be written in English with numerals and letter suffixes: 1st, 2nd or 2d, 3rd or 3d, 4th, 11th, 21st, 101st, 477th, etc., with the suffix acting as an ordinal indicator.

In this tutorial we’ll discuss how to display numbers with ordinal suffix like 1st, 2nd, 3rd,4th,etc.


public function ordinal($number) 
    $ends = array('th','st','nd','rd','th','th','th','th','th','th');
    if ((($number % 100) >= 11) && (($number%100) <= 13))
       return $number. 'th';
       return $number. $ends[$number % 10];
echo ordinal('5');

Explanation :

Above example,

  1. Define a function named ordinal() with a parameter $number.
  2. Declare suffix as an array and define to a variable.
  3. if $number % 100 greater than or equal to 11 and $number % 100 is less than or equal to 13 that is, $number % 100 is in between 11 and 13 it’s suffix is considered as ‘th’.
  4. else find the $number % 10 th index of suffix array.

For other php solutions please visit Php

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top