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.

PHP :

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';
    else
       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

Related Posts

forest fire

Forest Fire – Techgig, All testcases passed. Challenge #1

Forest Fire (100 Marks) Challenge 1: Forest fire You are camping in a forest area at night. You are living with the forest officers to experience their challenges…

the magic wand

The Magic Wand – TechGig PHP answer, all test cases passed. Challenge #2

The Magic Wand – TechGig PHP answer – all testcases passed The Magic Wand (100 Marks) You are a wizard who possesses the magic wand that can be…

PHP interview Questions and Answers

What is PHP? Answer: PHP stands for Hypertext Preprocessor. It is a widely used server-side scripting language primarily designed for web development. PHP code is embedded within…

install php

A Step-by-Step Guide on How to Install PHP

Install PHP : A Step-by-Step Guide on How to Install PHP Introduction: PHP is a widely used server-side scripting language that powers countless websites and web applications….

what is php

What is PHP? Understanding PHP: The Powerhouse of Web Development

Introduction: What is PHP? Understanding PHP: The Powerhouse of Web Development: In the world of web development, PHP stands tall as one of the most widely-used and…

php form

Complete Php form example

Here we are going to check how to create a php form and insert its values to database table. In this example we will be submitting the…

Leave a Reply

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