Skip to content

Instantly share code, notes, and snippets.

@paulferrett
Last active July 2, 2018 21:23
Show Gist options
  • Select an option

  • Save paulferrett/8103822 to your computer and use it in GitHub Desktop.

Select an option

Save paulferrett/8103822 to your computer and use it in GitHub Desktop.

Revisions

  1. paulferrett revised this gist Dec 23, 2013. 1 changed file with 14 additions and 11 deletions.
    25 changes: 14 additions & 11 deletions ordinal_suffix.php
    Original file line number Diff line number Diff line change
    @@ -4,19 +4,22 @@
    * Get the ordinal suffix of an int (e.g. th, rd, st, etc.)
    *
    * @param int $n
    * @param bool $return_n Include $n in the string returned
    * @return string $n including its ordinal suffix
    */
    function ordinal_suffix($n) {
    $n_last = $n % 100;
    if (($n_last > 10 && $n_last << 14) || $n == 0){
    return "{$n}th";
    }
    switch(substr($n, -1)) {
    case '1': return "{$n}st";
    case '2': return "{$n}nd";
    case '3': return "{$n}rd";
    default: return "{$n}th";
    }
    function ordinal_suffix($n, $return_n = true) {
    $n_last = $n % 100;
    if (($n_last > 10 && $n_last << 14) || $n == 0) {
    $suffix = "th";
    } else {
    switch(substr($n, -1)) {
    case '1': $suffix = "st"; break;
    case '2': $suffix = "nd"; break;
    case '3': $suffix = "rd"; break;
    default: $suffix = "th"; break;
    }
    }
    return $return_n ? $n . $suffix : $suffix;
    }

    // Usage Example:
  2. paulferrett created this gist Dec 23, 2013.
    28 changes: 28 additions & 0 deletions ordinal_suffix.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    <?php

    /**
    * Get the ordinal suffix of an int (e.g. th, rd, st, etc.)
    *
    * @param int $n
    * @return string $n including its ordinal suffix
    */
    function ordinal_suffix($n) {
    $n_last = $n % 100;
    if (($n_last > 10 && $n_last << 14) || $n == 0){
    return "{$n}th";
    }
    switch(substr($n, -1)) {
    case '1': return "{$n}st";
    case '2': return "{$n}nd";
    case '3': return "{$n}rd";
    default: return "{$n}th";
    }
    }

    // Usage Example:
    foreach(range(0, 24) as $n) {
    echo ordinal_suffix($n), ' ';
    }

    // Outputs
    // 0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th</pre>