开发者

add 'rd or 'th or 'st dependent on number [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Display numbers with ordinal suffix in PHP

I think they are called Ordinal suffixes.

Have seen examples for dates...

But just wondered if there was some php that can spew out the suffix dependant on number.

Example: we are spewing out the leaderboard score of our users.

So member ranked number 1. we wish to echo: 1'st and member ranked 847. we want to spew out 847'th

etc etc

I cannot give example, as the numbers are rendered on page via our dB

Just wondered if there was some sort of code snippet, that could add auto开发者_如何学Pythonmagically 'th or 'st or 'rd to the appropriate number.


I don't know of any built-ins that do this, but this should work:

function ordinal_suffix($num){
    $num = $num % 100; // protect against large numbers
    if($num < 11 || $num > 13){
         switch($num % 10){
            case 1: return 'st';
            case 2: return 'nd';
            case 3: return 'rd';
        }
    }
    return 'th';
}

(note 11, 12 and 13 are special cases - 11th, 12th, 13th vs 11st...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜