Website Administrator
Quick PHP Tips for the budding Website Administrator...
This is also posted on our blog.
Ordinal numbers are inclusive of the letters that appear after the number of the day. Eg. 1st, 2nd, 3rd, 4th etc.
Php already has a feature that will display this for you in it's date handling functions. This is today's example:
This code:
<?php echo date('dS'); ?>
will display this:
12th
And this is great. You can see that this code will show our ordinal suffix with ease.
But if you are calling this code between the 1st and 9th of the month, there is a leading zero which makes our date date look out of place. This is not how we write our dates in English. 01st, 03rd, etc.
So we want to extract the 0 from the front of these days. And we can do just that if we load the date into a variable and remove any encounter with a zero from the start of the variable. So if we have 0002, we just want the 2, or 06th, we get 6th.
And this is where Php's ltrim function comes in nicely. We can use it to trim anything we want from the start of a variable. We want to get rid of zeros and so we are going to use it to remove any of these that appear on the left (ltrim = left trim).
I like to display my date a certain way, so let's use that in this next example. You can see that the ordinal part of my code [dS] ends up in the second [1] variable. So make sure you point your code to the correct variable [x] in the second line if you change the display sequence. And now here is one way we can get our desired result with ltrim and explode:
This code:
<?php
$BlitDate = explode(" ", date('l, dS F Y'));
$BlitDate[1]= ltrim($BlitDate[1], "0");
echo "$BlitDate[0] ";
echo "$BlitDate[1] ";
echo "$BlitDate[2] ";
echo "$BlitDate[3] ";
?>
will display this:
Sunday, 12th January 2025
If you are running Php on a local computer, you can change your computer date to test that it works for any given day.
Also, some of you might not want to run this function on the date unless you really need to. After all, most days of the month don't need this trimming at all. So we can add an if statement so that we only run this for the first 9 days of the month like so:
This code:
<?php
$BlitDate = explode(" ", date('l, dS F Y'));
if ( $BlitDate[1] < 10 ) {$BlitDate[1]= ltrim($BlitDate[1], "0");
}
echo "$BlitDate[0] ";
echo "$BlitDate[1] ";
echo "$BlitDate[2] ";
echo "$BlitDate[3] ";
?>
will display this:
Sunday, 12th January 2025
And we are done, unless you want to download a strict xhml4/.php template with this last piece of code inside.
fin.