Web Development

This is a neat function I have used to create ordinal numbers in PHP.

``````function ordinalize(\$num) {
\$suff = 'th';
if ( ! in_array((\$num % 100), array(11,12,13))){
switch (\$num % 10) {
case 1:  \$suff = 'st'; break;
case 2:  \$suff = 'nd'; break;
case 3:  \$suff = 'rd'; break;
}
return "{\$num}{\$suff}";
}
return "{\$num}{\$suff}";
}
``````

It produces something like `1st`, `2nd`, and `3rd`. It works on all integers of course.

 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21th 22th 23th 24th 25th 26th 27th 28th 29th 30th 31th 32th 33th 34th 35th 36th 37th 38th 39th 40th 41th 42th 43th 44th 45th 46th 47th 48th 49th 50th
##### Let’s Try it Out

I wrote some PHP code to output ordinal numbers in tables like the one above but this one is until 100:

``````<?php function output (){
echo '<tr>';
foreach (range(1, 100) as \$number) {
echo '<td>';
echo ordinalize(\$number);
echo '</td>';
if (\$number % 10 == 0) {
echo "</tr><tr>";
}
}
}
```
```    function ordinalize(\$num) {
\$suff = 'th';
if ( ! in_array((\$num % 100), array(11,12,13))){
switch (\$num % 10) {
case 1:  \$suff = 'st'; break;
case 2:  \$suff = 'nd'; break;
case 3:  \$suff = 'rd'; break;
}
return "{\$num}{\$suff}";
}
return "{\$num}{\$suff}";
}
```
```?>
``````
``````<h3>Output:</h3>
<table class='table'>
<?php output();?>
</table>
``````
##### Live Example

Try it the sample for ordinal numbers in PHP with code included!