简体   繁体   中英

PHP- For loop not being accessed

So I have the following for loop:

$arr = [];
for($x = date('j', strtotime('this week')); $x <= date('j', strtotime('this week + 6 days')); $x++)
            {
                dd('test');
                $arr[$x] = [
                    'y' => $x,
                    's' => 0,
                    'c' => 0,
                    'cl' => 0
                ];
            }
            dd('test2');

The problem is that the loop is never accessed...the dd() returns 'test2' but the for loop is not accessed and it doesn't return any errors. I have a similar one:

for($x = 1; $x <= date('t', strtotime('today')); $x++)
            {
                $arr[$x] = [
                    'y' => $x . ' ' . date('M', strtotime('today')),
                    's' => 0,
                    'c' => 0,
                    'cl' => 0
                ];
            }

And this one works perfectly. What I am trying to do is generate indexes for $arr based on this week's days or in the following case based on this month's days. I simply don't understand why one works and the other doesn't. Thank you all for your time and help!

What you have with:

$x = date('j', strtotime('this week')); //returns 29

$x <= date('j', strtotime('this week + 6 days')) // returns 4

And never enter to the loop (the operation is: 29 < 4).

If you change the j for a z (in the PHP oficial documentation for date:

The day of the year (starting from 0)

) you will obtain the:

x: 148 < x: 154

Then, inside the loop, you can use the j to store the day of the week, and the loop will work.

If you want to go between 2 dates, adding days, there is others solutions too like: How to count days between two dates in PHP?

Hope it helps!

$date = new DateTime('this week Sunday');
$endDate = new DateTime('this week Saturday');

while( $date<=$endDate ){
   // do some stuff
   // ...

   $date->modify('+1 day');
}

Soution found due to @JP. Aulet's explanation:

for($x = 0; $x <= 6; $x++)
            {
                $date = date('j', strtotime('this week +' .$x . 'days'));
                $arr[$date] = [
                    'y' => $date,
                    's' => 0,
                    'c' => 0,
                    'cl' => 0
                ];
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM