I am trying to generate the range of days, from 1 to 28
, with the English ordinal suffix for the day of the month. For example: 1st of month
, 2nd of month
…
for($i = 1; $i <= 28; $i++) { $arrayRange[] = date('dS', strtotime($i)); } echo "<pre>"; print_r($arrayRange); echo "</pre>";
Output:
Array ( [0] => 01st [1] => 01st [2] => 01st ... [26] => 01st [27] => 01st )
What am I doing wrong..?
Advertisement
Answer
Try this, it uses the contextual date functionality of ‘+1 day’ etc to register your integer as a day ๐
To answer your second question – as in what you’re doing wrong – you’re passing an integer to a function that expects a string.
<?php for($i = 0; $i <= 27; $i++) { //The February is there to keep '1st' a '1st' even on days when it's not //the '31st' $arrayRange[] = date('dS', strtotime("1st february +".$i.' day')); } echo "<pre>"; print_r($arrayRange); echo "</pre>";
Output:
Array ( [0] => 01st [1] => 02nd ... [28] => 28th )ยจ
Edit:
To remove the 0s, you can use ltrim() like this:
$arrayRange[$i] = ltrim(date('dS', strtotime("1st february +".$i.' day')), "0");
Which will give you an output like this
[0] => 1st [1] => 2nd ... [28] => 28th
Edit 2: Fixed it. Props to MLF for noticing the mistake.