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);
Related
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;
i found some random code on the net and tried using it for my calendar but i keep getting this error:
Notice: Undefined variable: nextHoliday
this error is referring to the code at the end "RETURN $nextHoliday; "
I believe nextHoliday is defined tho so i tried a few things but nothing makes it work.. can someone please help?
Here's the code:
FUNCTION GetTimeStamp($MySqlDate)
{
$date_array = EXPLODE("-",$MySqlDate); // split the array
$var_year = $date_array[0];
$var_month = $date_array[1];
$var_day = $date_array[2];
$var_timestamp = MKTIME(0,0,0,$var_month,$var_day,$var_year);
RETURN($var_timestamp); // return it to the user
} // End function GetTimeStamp()
FUNCTION ordinalDay($ord, $day, $month, $year)
// ordinalDay returns date of the $ord $day of $month.
// For example ordinalDay(3, 'Sun', 5, 2001) returns the
// date of the 3rd Sunday of May (ie. Mother's Day).
//
// Note: $day must be the 3 char abbr. for the day, as
// given by date("D");
//
{
$firstOfMonth = GetTimeStamp("$year-$month-01");
$lastOfMonth = $firstOfMonth + DATE("t", $firstOfMonth) * 86400;
$dayOccurs = 0;
FOR ($i = $firstOfMonth; $i < $lastOfMonth ; $i += 86400)
{
IF (DATE("D", $i) == $day)
{
$dayOccurs++;
IF ($dayOccurs == $ord)
{ $ordDay = $i; }
}
}
RETURN $ordDay;
} // End function ordinalDay()
FUNCTION getNextHoliday()
// Looks through a lists of defined holidays and tells you which
// one is coming up next.
//
{
$year = DATE("Y");
CLASS holiday
{
VAR $name;
VAR $date;
VAR $catNum;
FUNCTION holiday($name, $date, $catNum)
// Contructor to define the details of each holiday as it is created.
{
$this->name = $name; // Official name of holiday
$this->date = $date; // UNIX timestamp of date
$this->catNum = $catNum; // category, we used for databases access
}
} // end class holiday
$holidays[] = NEW holiday("Groundhog Day", GetTimeStamp("$year-2-2"), "20");
$holidays[] = NEW holiday("Valentine's Day", GetTimeStamp("$year-2-14"), "14");
$holidays[] = NEW holiday("St. Patrick's Day", GetTimeStamp("$year-3-17"), "15");
$holidays[] = NEW holiday("Easter", EASTER_DATE($year), "16");
$holidays[] = NEW holiday("Mother's Day", ordinalDay(2, 'Sun', 5, $year), "3");
$holidays[] = NEW holiday("Father's Day", ordinalDay(3, 'Sun', 6, $year), "4");
$holidays[] = NEW holiday("Independence Day", GetTimeStamp("$year-7-4"), "17");
$holidays[] = NEW holiday("Christmas", GetTimeStamp("$year-12-25"), "13");
$numHolidays = COUNT($holidays);
FOR ($i = 0; $i < $numHolidays; $i++)
{
IF ( DATE("z") > DATE("z", $holidays[$i]->date) && DATE("z") <= DATE("z",
$holidays[$i+1]->date) )
{
$nextHoliday["name"] = $holidays[$i+1]->name;
$nextHoliday["dateStamp"] = $holidays[$i+1]->date;
$nextHoliday["dateText"] = DATE("F j, Y", $nextHoliday["dateStamp"]);
$nextHoliday["num"] = $holidays[$i+1]->catNum;
}
}
RETURN $nextHoliday;
} // end function GetNextHoliday
$nextHoliday = getNextHoliday();
ECHO $nextHoliday["name"]." (".$nextHoliday["dateText"].")";
You have one of two options. Either instantiate empty keys for your array values:
$nextHoliday = array();
$nextHoliday['name'] = '';
$nextHoliday['dateStamp'] = '';
$nextHoliday['dateText'] = '';
$nextHoliday['num'] = '';
$numHolidays = COUNT($holidays);
for ($i = 0; $i < $numHolidays; $i++) {
// ... Blah
}
Or use isset before each array lookup:
echo (isset($nextHoliday['name'] ? $nextHoliday['name'] : '') .
" (" .
(isset($nextHoliday) ? $nextHoliday["dateText"] : '' ) .
")";
Nothing better than the ternary operator for inline conditionals.
It's actually good that we're testing this in January, because otherwise this bug would have bitten you later on. The problem is that you are using less than/greater than to determine what the next holiday is. This fails to take into account the last holiday of the last year.
To fix this, the variable $lastHoliday needs to be a negative representation of the last holiday:
$numHolidays = COUNT($holidays);
$nextHoliday = array('name' => '', 'dateStamp' => '', 'dateText' => '', 'num' => '');
for ($i = 0; $i < $numHolidays - 1; $i++) {
$today = DATE("z");
if ($i == 0) {
$lastHoliday = (365 - DATE("z", $holidays[$numHolidays - 1]->date)) * -1;
} else {
$lastHoliday = DATE("z", $holidays[$i]->date);
}
$futureHoliday = DATE("z", $holidays[$i+1]->date);
//print_r($today); echo "<br />";
//print_r($lastHoliday); echo "<br />";
//print_r($futureHoliday); echo "<br />";
if ($today > $lastHoliday && $today <= $futureHoliday ) {
$nextHoliday["name"] = $holidays[$i+1]->name;
$nextHoliday["dateStamp"] = $holidays[$i+1]->date;
$nextHoliday["dateText"] = DATE("F j, Y", $nextHoliday["dateStamp"]);
$nextHoliday["num"] = $holidays[$i+1]->catNum;
}
}
Also consider typing PHP in lowercase, not uppercase, as it is an almost universal standard in PHP. One true brace style wouldn't hurt either.
$nextHoliday is used in a if but is not declared
Declare the variable before the for:
[...]
$nextHoliday = array();
FOR ($i = 0; $i < $numHolidays; $i++)
[...]
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>";
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generate incrementing date strings
I have:
$start_date = '2012-09-03';
$number_days = 5;
I would like receive array with this dates:
$dates = array(
'2012-09-03',
'2012-09-04',
'2012-09-05',
'2012-09-06',
'2012-09-07'
);
What is the best way for this?
$start_date = '2012-09-03';
$dates[] = $start_date;
$number_days = 5;
for ($i=1; $i < $number_days; $i++) {
$dates[] = date('Y-m-d', strtotime("$start_date +$i days"));
}
http://php.net/manual/en/function.date-add.php
Loop over and add the dates you need.
Have you tried something like this
function get_days($start_date, $max){
$ts=strtotime($start_date);
$next_day_interval=24*60*60;
$arr=array();
$arr[]=$start_date;
for($i=1;$i<=$max;$i++){
$ts += $next_day_interval;
$arr[]=date('Y-m-d', $ts);
}
return $arr;
}
Just wrote it here so there might be some compile time errors but I hope you get the idea.
Here's what you're searching for (work also on PHP < 5.3)
<?php
$start_date = '2012-09-03';
$number_days = 5;
$stdate = date(strtotime($start_date));
$dates = array();
for($i = 0 ; $i < $number_days ; $i++) {
$dates[$i] = date('Y-m-d', $stdate) ;
$stdate += 24*60*60;
}
var_dump($dates);
?>
Try this.
$start_date = '2012-09-03';
$number_days = 5;
$dates = array();
$TS = strtotime($start_date);
$dates[0] = $start_date;
for($i=1;$i<5;$i++)
{
$dates[$i] = date('Y-m-d', strtotime('+1 day', $TS));
$TS = strtotime($dates[$i]);
}
Modified Code from #vinay to print actual output
<?php
$start_date = '2012-09-03';
$number_days = 5;
$dates = array();
$TS = strtotime($start_date);
for($i=0;$i<5;$i++)
{
$dates[$i] = date('Y-m-d', strtotime('+1 day', $TS));
$TS = strtotime($dates[$i]);
echo date('y-m-d',$TS).'<br>';
}
?>
Here is simple example with PHP 5.3 DateTime and DateInterval. This is clear solution. Note: PHP 5.2 supports DateTime, but not DateInterval. You may declare it in custom class in PHP 5.2, see here: DateInterval Definition.
<?php
$start_date = '2012-09-03';
$number_days = 5;
$dt = new DateTime($start_date);
$dates = array();
for($i = 0; $i < $number_days; $i++) {
$dates[] = $dt->format("Y-m-d");
$dt->add(new DateInterval("P1D"));
}
print_r($dates);
?>
I'm struggling with how to build the following:
result I need:
$months = array();
$months
(
month[0] = '2011-10-1'
month[1] = '2011-11-1'
month[2] = '2011-12-1'
month[3] = '2012-1-1'
)
from the following variables:
$date = '2011-10-1';
$numberOfMonths = 4;
Any help would be appreciated.
Thanks, guys... all of these solutions work. I accepted the one that works best for my usage.
You can do it using a simple loop and strtotime():
$date = '2011-10-1';
$numberOfMonths = 4;
$current = strtotime($date);
$months = array();
for ($i = 0; $i < $numberOfMonths; $i++) {
$months[$i] = date('Y-n-j', $current);
$current = strtotime('+1 month', $current);
}
$date = DateTime::createFromFormat('Y-m-j', '2011-10-1');
$months = array();
for ($m = 0; $m < $numberOfMonths; $m++) {
$next = $date->add(new DateInterval("P{$m}M"));
$months[] = $next->format('Y-m-j');
}
<?php
function getNextMonths($date, $numberOfMonths){
$timestamp_now = strtotime($date);
$months[] = date('Y-m-d', $timestamp_now);
for($i = 1;$i <= $numberOfMonths; $i++){
$months[] = date('Y-m-d', (strtotime($months[0].' +'.$i.' month')));
}
print_r($months);
}
getNextMonths('2011-10-1', 4);
Working demo
You could use split on date and then a for loop over the month. The trick is to use something like
$newMonth = ($month + $i) % 12 + 1;
(% is called modulo and does exactly what you want.)