Looping through an array with PHP - php

I want to use PHP to populate an array starting with today's date and going several days into the future. When I tried the following below all of the columns contain "2013-11-18." I have been toying with it for 2 hours, but to no avail. What am I missing?
//Get "Day 0", today if undefined
if(isset($_GET['DAY0']) == TRUE){
$day0 = new DateTime($_GET['DAY0']);
} else {
$day0 = new DateTime('today');
}
// save day0 + 7 days into into dayArray
$dayArray[0] = $day0;
for($i=1; $i<8; $i++){
$day0->modify('+1 day');
$dayArray[i]= $day0;
}
echo "<tr>";
for ($i = 0; $i < 7; $i++) {
echo "<th>".$dayArray[i]->format('Y-m-d')."</th>";
}
echo "</tr>";

Objects are passed by reference. You are assigning multiple references to the same object in your array.
If you really need all the datetime objects in the array, you could do something like this
$interval = new DateInterval('P1D');
$start = new DateTime('today');
$dayArray = [clone $start];
for ($i = 1; $i < 8; $i++) {
$dayArray[] = clone $start->add($interval);
}
Or you could just store the formatted dates as already suggested.
$interval = new DateInterval('P1D');
$start = new DateTime('today');
$dayArray = [$start->format('Y-m-d')];
for ($i = 1; $i < 8; $i++) {
$dayArray[] = $start->add($interval)->format('Y-m-d');
}

Replace two of your $dayArray[i] with $dayArray[$i]

You could save timestamps:
// save day0 + 7 days into into dayArray
$dayArray[0] = $day0->format('U');
for($i=1; $i<8; $i++){
$day0->modify('+1 day');
$dayArray[$i] = $day0->format('U');
}
echo "<tr>";
for ($i = 0; $i < 7; $i++) {
echo "<th>".date('Y-m-d', $dayArray[$i])."</th>";
}

You can create a DatePeriod like so:
if(isset($_GET['DAY0']) == TRUE){
$day0 = new DateTime($_GET['DAY0']);
} else {
$day0 = new DateTime('today');
}
$enddate = new DateTime();
$period = new DatePeriod(
$day0,
new DateInterval('P1D'),
$enddate->add(new DateInterval('P7D'))
);
echo "<tr>";
foreach ($period as $datetime) {
echo "<th>".datetime->format('Y-m-d')."</th>";
}
echo "</tr>";

Related

How to show days of the first week of the year?

Hello i have this code:
$anno = 2020;
$settimana = 53;
$anno2 = 2021;
$settimana2 = 1;
for($i = 1; $i <= 7; $i++){
$giorno = date('d/m/Y', strtotime($anno."W".$settimana.$i));
echo $giorno."<br>";
}
echo "<br><hr><br>";
for($i = 1; $i <= 7; $i++){
$giorno2 = date('d/m/Y', strtotime($anno2."W".$settimana2.$i));
echo $giorno2."<br>";
}
This is the output of first loop:
28/12/2020
29/12/2020
30/12/2020
31/12/2020
01/01/2021
02/01/2021
03/01/2021
This is the output of the second loop
15/03/2021
22/03/2021
29/03/2021
05/04/2021
12/04/2021
19/04/2021
26/04/2021
But i wait this output
04/01/2021
05/01/2021
06/01/2021
07/01/2021
08/01/2021
09/01/2021
How can i resolve the problem?
You can try this function
Modify this function as your requirements.
Create array of whole week by running a loop from 1 to 6 days.
you will get your required result.
function getStartAndEndDate($week, $year) {
$dto = new DateTime();
$dto->setISODate($year, $week);
$ret['week_start'] = $dto->format('Y-m-d');
$dto->modify('+6 days');
$ret['week_end'] = $dto->format('Y-m-d');
return $ret;
}
$week_array = getStartAndEndDate(1,2021);
print_r($week_array);
//output
Array
(
[week_start] => 2021-01-04
[week_end] => 2021-01-10
)
EDIT:
I checked your code and i think problem is with $settimana2 = 1; change this variable to $settimana2 = 01;

PHP: Creating default object from empty value

I am having a problem with this code:
$days = array();
$d = new StdClass;
for($i = 0; $i < 7; $i++){
$day = date("Y-m-d", strtotime("-".$i." day"));
$d->x = $day; //error
$days[] = $d;
unset($d);
}
dd($days);
Even thought I have declared a new object it shows me error:
Creating default object from empty value.
How could i possibly resolve this problem?
Try this, Hope this will help you out. You should define $d = new StdClass; with in the loop. For initiating a new object everytime.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$days = array();
for ($i = 0; $i < 7; $i++)
{
$d = new StdClass;
$day = date("Y-m-d", strtotime("-" . $i . " day"));
$d->x = $day; //error
$days[] = $d;
unset($d);
}
print_r($days);

Wrong Data in Month Array

What I can do if would like start my January month since 2016-01-01 not 2016-01-02.
https://3v4l.org/uRRfU
function countDaysForChoosenYears(int $year):int
{
$att = [];
for ($i = 1; $i <= 12; $i++) {
$att[] = cal_days_in_month(CAL_GREGORIAN, $i, $year);
}
$att = array_sum($att);
return $att;
}
$YearMonthDayStructure = [];
$Date = new DateTime('2016-01-01');
for ($i = 1; $i <= countDaysForChoosenYears(2016); $i++) {
$monthName = $Date->format('F');
$yearNumber = $Date->format('Y');
$YearMonthDayStructure[$yearNumber][$monthName][$Date->format('d')] = $Date->add(new DateInterval('P1D'))->format('Y-m-d');
}
print_r($YearMonthDayStructure);
The very first time you enter the loop you are adding P1D to the date. So your first date ends up being 2 Jan because you added P1D to 1 Jan on that line with the $Date->add. It's not like $x++ where the '++' happens after you use the variable. It performs the add and then gives the result, with the added P1D, to the $YearMonthDayStructure value.

Values not generating for last month in datetime php

I am trying to get the number of sat&sun for each month between two given dates.
eg: For start_date as 5-Jul-2015 and end_date as 29-Aug-2015 I need to get 7 sat&sun in Jul and 9 in Aug.
So far I am getting values till the second last month ie: not getting Aug.
What to do?
Code
$countSat = 0;
$countSun = 0;
$start = new DateTime('05-07-2015');
$month = $start->format('n');
$end = new DateTime('29-08-2015');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
$i = 0;
foreach ($period as $dt) {
if ($month != $dt->format('n')) {
$results[$i] = $countSun + $countSat;
$i++;
$countSun = 0;
$countSat = 0;
}
if ($dt->format('N') == 7) {
$countSun++;
}
if ($dt->format('N') == 6) {
$countSat++;
}
$month = $dt->format('n');
}
echo '<pre>';
print_r($results);
You are forgetting to add the results after the loop is done. The month will only change from 7 to 8 inside the loop.
Thus the days of the last month are being counted but never added.
$countSat = 0;
$countSun = 0;
$start = new DateTime('05-07-2015');
$month = $start->format('n');
$end = new DateTime('29-08-2015');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
$i = 0;
foreach ($period as $dt) {
if ($month != $dt->format('n')) {
$results[$i] = $countSun + $countSat;
$i++;
$countSun = 0;
$countSat = 0;
}
if ($dt->format('N') == 7) {
$countSun++;
}
if ($dt->format('N') == 6) {
$countSat++;
}
$month = $dt->format('n');
}
$results[$i] = $countSun + $countSat;
echo '<pre>';
print_r($results);

unexpected while-loop behavior

I've tried building and placing the while loop in different ways and different locations and looking at $val as the right/wrong variable to be placing in the while loop but I'm just not getting it. I expected output to be: 815 830 845 900....... until reaching 1900.
Instead I got 815 then 1915 1930 1945 up through 0000 then it cycles over starting at 1915. Someone please tell me what i have placed in the wrong location or what variable I've used wrongly.
date_default_timezone_set('America/New_York');
$st='800';
$et='1900';
$frac = 900;
$x = $et;
$val=0;
if (strlen($st) < 4) {$st = "0".$st;}
$current_time = strtotime(date($st));
$r = $current_time % $frac;
$new_time = $current_time + ($frac-$r);
$val = date('Gi', $new_time);
echo $val."<br>";
while ($val !== $et){
if (strlen($val) < 4) {$st = "0".$val;}
$current_time = strtotime('+ 15 minutes',date($val));
$r = $current_time % $frac;
$new_time = $current_time + ($frac-$r);
$val = date('Gi', $new_time);
echo $val."<br>";
}
NOTE TO THE - MARKDOWN PLAYERS -- Edited POST ANSWER: You can bash the question all you want, but the fact is it was a clear question, clear objective trying to be reached and it was a clear attempt (one of several) to code it properly that failed, so bad code, not bad effort. So eventually I asked for help. Your using the markdown system the wrong way and for the wrong reason, but whatever I have little expectation that you care. Thanks to those that made the effort actually be constructive and teach/help.
With unelegant for loop:
for ($i = 800, $t= 1900; $i <= $t; $i += 15) {
printf('%1$3d <br>', $i);
if ($i%100 >= 45) $i += 40;
}
With DatePeriod:
$timezone = new DateTimeZone("America/New_York");
$begin = new DateTime("now", $timezone);
$begin->setTime(8, 0, 0);
$end = new DateTime("now", $timezone);
$end->setTime(19, 0, 0);
$interval = new DateInterval('PT15M');
$end->add($interval);
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
echo $date->format("Gi") . "<br>";
}
With generators:
function xmins($start, $end, $step = 15) {
if ($start < $end) {
if (($step <= 0) || ($step >= 40)) {
throw new LogicException('Step must be in range 1-40');
}
for ($i = $start; $i <= $end; $i += $step) {
if (60 <= $temp = $i % 100) {
$i += 40;
}
yield $i;
if ((60-$step) === $temp = $i % 100) {
$i += 100 - $temp - $step;
}
}
}
}
foreach (xmins(800,1900,15) as $i) {
printf('%1$3d<br>', $i);
}
Using DateInterval:
$date = new DateTime('2015-01-01 08:00:00');
$mins = new DateInterval('PT15M');
do {
$date->add($mins);
echo $date->format('Hi')."\n";
} while($date->format('Hi') < 1900);

Categories