PHP Generate day range

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..?
Answer
Solution:
You should pass correct timestamp as the second parameter of date function and usej
(without leading zero) day format:
list($m, $y) = explode('-', date('m-Y'));
for($d = 1; $d <= 28; $d++)
{
$arrayRange[] = date('jS', mktime(0, 0, 0, $m, $d, $y));
}
echo "<pre>";
print_r($arrayRange);
echo "</pre>";
Answer
Solution:
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.
Answer
Solution:
You can use something like this:
$arrayRange[] = (new DateTime('Aug '.$i))->format('jS');
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: filter_sanitize_string deprecated
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.