views:

130

answers:

3

hi . its different problem , i want to display numbers as follows

1 as 1st, 2 as 2nd and so on to 150 as 150th. the problem is how to find 'st' , 'nd' ,'rd' and 'th' for numbers through code

+9  A: 

from http://www.phpro.org/examples/Ordinal-Suffix.html

<?php

/**
 *
 * @return number with ordinal suffix
 *
 * @param int $number
 *
 * @param int $ss Turn super script on/off
 *
 * @return string
 *
 */
function ordinalSuffix($number, $ss=0)
{

    /*** check for 11, 12, 13 ***/
    if ($number % 100 > 10 && $number %100 < 14)
    {
        $os = 'th';
    }
    /*** check if number is zero ***/
    elseif($number == 0)
    {
        $os = '';
    }
    else
    {
        /*** get the last digit ***/
        $last = substr($number, -1, 1);

        switch($last)
        {
            case "1":
            $os = 'st';
            break;

            case "2":
            $os = 'nd';
            break;

            case "3":
            $os = 'rd';
            break;

            default:
            $os = 'th';
        }
    }

    /*** add super script ***/
    $os = $ss==0 ? $os : '<sup>'.$os.'</sup>';

    /*** return ***/
    return $number.$os;
}
?> 
John Boker
+8  A: 

Hi, from wikipedia:

$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($number %100) >= 11 && ($number%100) <= 13)
   $abbreviation = $number. 'th';
else
   $abbreviation = $number. $ends[$number % 10];

Where $number is the number you want to write. Works with any natural number.

Iacopo
Lovely solution
Tom Gullen
+1 for using the array, the duct tape of the universe :)
Lukman
Although a bit difficult to understand at first, I do now think it best represents how the ordinal suffix system works for English.
erisco
+4  A: 

Here is a one-liner:

$a = <yournumber>;
echo $a.substr(date('jS', mktime(0,0,0,1,($a%10==0?9:($a%100>20?$a%10:$a%100)),2000)),-2);

Probably the shortest solution. Can of course be wrapped by a function:

function ord($a) {
  // return English ordinal number
  return $a.substr(date('jS', mktime(0,0,0,1,($a%10==0?9:($a%100>20?$a%10:$a%100)),2000)),-2);
}

Regards, Paul

EDIT1: Correction of code for 11 through 13.

EDIT2: Correction of code for 111, 211, ...

EDIT3: Now it works correctly also for multiples of 10.

Paul
I like this approach, but alas, it doesn't work :-(30th comes out as 30st. 40th comes out as 40st. etc.
Jamie
Yeah, sorry. When I read the question I thought, hey this should be possible by a single line of code. And I just typed it away. As you see from my edits, I'm improving. After the third edit now I think it's quite done. At least all numbers from 1 to 150 print out nicely on my screen.
Paul
Looks good up to 500! (haven't tested it further than that). Good work! :-)
Jamie
Thanks! ;) I like these brain-teasing tasks.
Paul