-4

For eg. If I enter 1 the result will be first and if I enter 5, the result will be fifth

I really don't get any idea about how to solve this problem. Please help me to solve this problem.

Donkarnash
  • 12,433
  • 5
  • 26
  • 37

1 Answers1

2

If you are talking about ordinal suffix, then for PHP 5.3+, the built-in Number Formatter can be used

$numbers = [1,2,3,4,5,67,789];
$formatter = new NumberFormatter('en-US', NumberFormatter::ORDINAL);

foreach($numbers as $num) {
    echo $formatter->format($num);
    echo PHP_EOL;
}

/**
//Will output the following

1st
2nd
3rd
4th
5th
67th
789th
*/

And if you want the result in words as first, fifth and so on you can


$formatter = new NumberFormatter('en-US', NumberFormatter::SPELLOUT);
$formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%spellout-ordinal");

$numbers = [1,2,3,4,5,21,67,789,2041];

foreach($numbers as $num) {
    echo echo $num . ": " .$formatter->format($num);
    echo PHP_EOL;
}

/**
Will output
1: first
2: second
3: third
4: fourth
5: fifth
21: twenty-first
67: sixty-seventh
789: seven hundred eighty-ninth
2041: two thousand forty-first
*/
Donkarnash
  • 12,433
  • 5
  • 26
  • 37