Jump to content

[SOLVED] Number st nd rd th


almightyegg

Recommended Posts

quick example from top of my head

 

$day = 22; //example

$NewDay = $day."th";

if($day == 1 || $day == 21 || $day == 31)
{
$NewDay = $day."st";
}
if($day == 2 || $day == 22)
{
$NewDay = $day."nd";
}
if($day == 3 || $day == 23)
{
$NewDay = $day."rd";
}

Not sure where I found this, I don't think its mine.

 

<?php

  function ordinal($n) {
    $ln = (int) substr($n, -1);
    $sln = (int) substr($n, -2);
    $r = array('st','nd','rd');
    $es = (($sln < 11 || $sln > 19) && $ln > 0 && $ln < 4);
    return $n . ($es ? $r[$ln - 1] : 'th');
  }

?>

A majority of them are going to be "th", so the best way to do with is check for ones that won't be "th."

 

$suffix = "th"
$lastdigit = strlen($num)-1;
if ($num[$lastdigit-1] != 1)
{
  if ($num[$lastdigit] == 1)
     $suffix = "st";
  else if ($num[$lastdigit] == 2)
     $suffix = "nd";
  else if ($num[$lastdigit] == 3)
     $suffix = "rd";
}

Oh, haha. That is because it doesn't check the size of the number, woops.

$suffix = "th"
$lastdigit = strlen($num)-1;
if ($num[$lastdigit-1] != 1 || $lastdigit == 0)
{
   if ($num[$lastdigit] == 1)
      $suffix = "st";
   else if ($num[$lastdigit] == 2)
      $suffix = "nd";
   else if ($num[$lastdigit] == 3)
      $suffix = "rd";
}

That should fix it.

It still echoes 1th, and I changed it a little bit after seeing it hadn't worked and made it more readable for myself as I'm a bit of a n00b....still

 

$lastdigit = strlen($num)-1;
if ($num[$lastdigit-1] != 1 || $lastdigit == 0)
{
   if($num[$lastdigit] == 1){
      $suffix = "st";
   }elseif($num[$lastdigit] == 2){
      $suffix = "nd";
   }elseif($num[$lastdigit] == 3){
      $suffix = "rd";
   }else{
      $suffix = "th";
}
}

@Thrope - That doesn't seem to have worked

 

Works fine here.

 

<?php

  function ordinal($n) {
    $ln = (int) substr($n, -1);
    $sln = (int) substr($n, -2);
    $r = array('st','nd','rd');
    $es = (($sln < 11 || $sln > 19) && $ln > 0 && $ln < 4);
    return $n . ($es ? $r[$ln - 1] : 'th');
  }

  foreach(range(1,100) as $v) {
    echo ordinal($v) . "<br />";
  }

?>

Woops, sorry, I am just not thinking. I was using the number as a string. Change it to this and it should work.

$num = (string)$num;
$suffix = "th";
$lastdigit = strlen($num)-1;
if ($lastdigit == 0 || $num[$lastdigit-1] != 1)
{
   if ($num[$lastdigit] == 1)
      $suffix = "st";
   else if ($num[$lastdigit] == 2)
      $suffix = "nd";
   else if ($num[$lastdigit] == 3)
      $suffix = "rd";
}

 

I switched the comparisons around so that it wouldn't give an warning if $lastdigit was 0.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.