I have a php script here to create login at our datacenter for myself, but this script is doing the login for next week if i run it after 12:00 on monday, and a lot of times I'm not there the whole week, so I want to improve this script by asking for user input and pass the dates that I will be there so the script only picks up on those dates. I know i have to do this with stdin and I do have a part that works, but i have no idea on how to integrate this into the current script and how to make sure i can give multiple dates
My stdin part that does ask my for a date, but no idea on how to combine it:
<?php
function promptDateFromUser(string $prompt, string $dateFormat): DateTimeInterface
{
echo "{$prompt} [$dateFormat]: ";
$stdin = fopen('php://stdin', 'r');
$line = trim(fgets(STDIN));
fclose($stdin);
$dateTime = DateTimeImmutable::createFromFormat('Y-m-d', $line);
if (! $dateTime instanceof DateTimeInterface) {
throw new UnexpectedValueException('Invalid datetime format');
}
}
$dateTime = promptDateFromUser("Please insert date:", 'Y-m-d');
?>
My login script as of now:
<?php
require 'shared.php';
restore_exception_handler();
restore_error_handler();
$md = new RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$date = new DateTime();
$hour = (int)$date->format('H');
$dow = (int)$date->format('w');
if (($dow === 1 && $hour > 12) || ($dow > 1 && $dow < 6)) {
$add = 'P' . (8 - $dow) . 'D';
$date->add(new DateInterval($add));
}
if (($dow === 1 && $hour <= 12) || $dow === 0 || $dow === 6) {
if ($dow === 6) {
$date->add(new DateInterval('P2D'));
} elseif ($dow === 0 ) {
$date->add(new DateInterval('P1D'));
}
}
$tomorrow = $date->format('Y-m-d');
$duration = 720;
$customerId = 30;
$purpose = 'DCG visit';
$phoneNumber = '';
$name = 'SOME NAME, REMOVED FOR PUBLICATION';
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
for ($x = 0; $x < 5; $x++) {
$start = $tomorrow." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested for: ", $tomorrow, PHP_EOL;
$date->add(new DateInterval('P1D'));
$tomorrow = $date->format('Y-m-d');
}
?>
I'm a big php noob, so some explanation is greatly appreciated!
after some help from a friend, i managed to solve this:
#!/usr/bin/env php
<?php
include('shared.php');
restore_exception_handler();
restore_error_handler();
// Constants
$timeout = 45;
$md = new \RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$duration = "720";
$customerId = "30";
$purpose = "DCG visit";
$phoneNumber = "";
$name="SOME NAME, REMOVED FOR PUBLICATION";
// Functions
function requestInput($msg) {
global $timeout;
echo "$msg\n\nThe timeout for this selection is $timeout seconds.\n\n> ";
$fd = fopen('php://stdin', 'r');
$read = array($fd);
$write = $except = array(); // we don't care about this
if(stream_select($read, $write, $except, $timeout)) {
$choice = trim(fgets($fd));
}
echo "\nYou typed: $choice\n\n";
return $choice;
}
// Start of program
$date = new DateTime();
$weekchoice = (int)requestInput("Which week would you like to request access for?\n1) Current week\n2) Next week\n3) Specific week number");
if ($weekchoice == 3) {
$weeknumber = (int)requestInput("Please enter a numeric week number");
} else {
$weeknumber = (int)$date->format("W");
if ($weekchoice == 2) {
$weeknumber += 1;
}
}
// We override $date with the start of the chosen week
$date->setISODate($date->format("Y"), $weeknumber);
echo "Thanks, you chose week $weeknumber which starts with " . $date->format("l d F, Y") . " \n\n";
$dayschoice = requestInput("Please enter the days you want access, as a space separated list:\n1) Monday\n2) Tuesday\n3) Wednesday\n4) Thursday\n5) Friday\n\nExample: 1 3 5");
$daylist = explode(' ', $dayschoice);
$processedDays = [];
foreach ($daylist as $eachday) {
$iday = (int)$eachday;
if ($iday == 0 || $iday % 7 == 0) { // No Sundays, also (int)"" -> 0, which is terrible
continue;
}
$add_days = $iday - 1; // Sums 0 if Monday, 1 if Tuesday and so on...
$newdate = new DateTime($date->format("Y-m-d"));
$newdate->modify("+$add_days days");
$processedDays[] = $newdate;
$formatted = $newdate->format("l d F Y");
echo "Processing day $iday, which is $formatted\n";
}
$hour = $date->format('H');
$tomorrow = $date->format('Y-m-d');
$confirm = requestInput("\nRequest access for these days? Yes/No");
if ($confirm != "Yes") {
echo 'Good bye!';
exit(0);
}
foreach ($processedDays as $reqDay) {
echo "Submitting " . $reqDay->format("l d F Y") . "\n";
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
}
foreach ($processedDays as $reqDay) {
$start = $reqDay->format('Y-m-d')." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested: ", $reqDay->format('l d F Y'), PHP_EOL;
$tomorrow = $date->format('Y-m-d');
}
?>
Related
I have a script to display business hours for three days from today.
The script works fine, but now I want to display if we are currently open or closed.
If the current time is after the closing time OF TODAY ($openingsuur_vandaag[1]) I would like to display "CLOSED".
Let's start with the script:
<?php
$i = 0;
$periodes = array();
$periodes[$i]['start'] = '2020-01-01';
$periodes[$i]['stop'] = '2020-12-31';
$periodes[$i]['open'] = array(null,"10:00","09:00","09:00","09:00","09:00","10:00");
$periodes[$i]['dicht'] = array(null,"16:00","10:00","18:00","18:00","14:00","15:00");
$periodes[$i]['behalve'] = array();
$periodes[$i]['behalve'][0]['dag'] = "2020-06-01";
$periodes[$i]['behalve'][0]['open'] = null;
$periodes[$i]['behalve'][0]['dicht'] = null;
$i++;
echo getOpeningsuren(time(), $periodes);
function getOpeningsuren($date, $periodes)
{
$resultaat = '';
$a = date("d-m-Y");
$b = date("d-m-Y",strtotime('tomorrow'));
$c = date("d-m-Y",strtotime('tomorrow + 1 day'));
$m_nu = new datum();
$m_morgen = new datum();
$m_morgen->add(0,0,1);
$m_overmorgen = new datum();
$m_overmorgen->add(0,0,2);
$openingsuur_vandaag = getOpeningsuur($m_nu, $periodes);
$openingsuur_morgen = getOpeningsuur($m_morgen, $periodes);
$openingsuur_overmorgen = getOpeningsuur($m_overmorgen, $periodes);
$resultaat = $resultaat . $a. ' '. ($openingsuur_vandaag[0] == null ? 'gesloten' :
$openingsuur_vandaag[0].' - '. $openingsuur_vandaag[1].' uur') .'<br>';
$resultaat = $resultaat . $b. ' '. ($openingsuur_morgen[0] == null ? 'gesloten' :
$openingsuur_morgen[0].' - '. $openingsuur_morgen[1].' uur') .'<br>';
$resultaat = $resultaat . $c. ' '. ($openingsuur_overmorgen[0] == null ? 'gesloten' :
$openingsuur_overmorgen[0].' - '. $openingsuur_overmorgen[1].' uur') .'';
return $resultaat;
}
function getOpeningsuur($date, $periodes)
{
$periodestart = new datum();
$periodestop = new datum();
foreach ($periodes as $periode)
{
$periodestart->setDatetime($periode["start"] ." 00:00:00");
$periodestop->setDatetime($periode["stop"] ." 00:00:00");
if ($date->getTime() < $periodestart->getTime())
continue;
if ($date->getTime() > $periodestop->getTime())
continue;
foreach ($periode['behalve'] as $uitzondering)
{
if ($date->getDate() == $uitzondering['dag'])
{
return array($uitzondering['open'], $uitzondering['dicht'] );
}
}
return array($periode['open'][ $date->dag_vd_week() ], $periode['dicht'][ $date->dag_vd_week() ] );
}
return array(null, null);
}
class datum
{
function datum( $tijd=0 )
{
($tijd ? $tijd=$tijd : $tijd = time() );
$this->dagen_kort = array("zo", "ma", "di", "wo", "do", "vr", "za" );
$this->setTime( $tijd );
}
var $jaar;
var $maand;
var $dag;
var $uur;
var $minuut;
var $seconde;
var $dagen_kort;
function setTime( $time )
{
$this->jaar = date("Y", $time);
$this->maand = date("m", $time);
$this->dag = date("d", $time);
$this->uur = date("H", $time);
$this->minuut = date("i", $time);
$this->seconde = date("s", $time);
}
function getTime()
{
return mktime($this->uur, $this->minuut, $this->seconde, $this->maand, $this->dag, $this->jaar);
}
function setDatetime($datetime)
{
$dt = explode (" ", $datetime);
list($this->jaar, $this->maand, $this->dag) = explode("-", $dt[0]);
list($this->uur , $this->minuut, $this->seconde) = explode(":", $dt[1]);
}
function getDate()
{
return str_pad($this->jaar, 4, "0", STR_PAD_LEFT) .'-'. str_pad($this->maand, 2, "0", STR_PAD_LEFT)
.'-'. str_pad($this->dag, 2, "0", STR_PAD_LEFT);
}
function dag_vd_week()
{
return date("w", $this->getTime());
}
function setVars($jaar=-1, $maand=-1, $dag=-1, $uur=-1, $minuut=-1, $seconde=-1)
{
($jaar > -1 ? null : $this->jaar = $jaar);
($maand > -1 ? null : $this->jaar = $maand);
($dag > -1 ? null : $this->jaar = $dag);
($uur > -1 ? null : $this->jaar = $uur);
($minuut > -1 ? null : $this->jaar = $minuut);
($seconde > -1 ? null : $this->jaar = $seconde);
}
function add($jaar=0, $maand=0, $dag=0, $uur=0, $minuut=0, $seconde=0)
{
$nieuwe_tijd = mktime($this->uur + $uur, $this->minuut + $minuut, $this->seconde + $seconde, $this-
>maand + $maand, $this->dag + $dag, $this->jaar + $jaar);
$this->setTime($nieuwe_tijd);
}
}
?>
In the first place, my solution was, but does not work :-(:
$OFFICETIME = date("h:i"); // current time
if ($openingsuur_vandaag[1] > $OFFICETIME ) { // today's closing time - current time
echo "closed";
}
else{echo "open";}
I have project built using laravel and a I have to build a function that counts all the complete quarters that are in the selected date range - the dates used are inserted via input.
Here are the quarters(i used numerical representations for the months)
01 - 03 first quarter
04 - 06 second quarter
07 - 09 third quarter
10 - 12 forth quarter
I would really appreciate your help,because I've been at it for an entire day now and basically have nothing to show for it,i thing I've been trying so hard i'm actually at the point where i'm so tired, i can t think straight.
I do have some code but it;s worthless, because it doesn't work, and any kind of idea or snippet of code is welcomed.
Thanks for your help in advance.
I managed to do this using multiple functions; basically, if this is needed for chart statistics, then a more specific approach might be the case.
I have done this in Laravel with timestamp dates as input (this code can be adapted for getting semesters also :) , it works and is already tested):
public static function getQuartersBetween($start_ts, $end_ts)
{
$quarters = [];
$months_per_year = [];
$years = self::getYearsBetween($start_ts, $end_ts);
$months = self::getMonthsBetween($start_ts, $end_ts);
foreach ($years as $year) {
foreach ($months as $month) {
if ($year->format('Y') == $month->format('Y')) {
$months_per_year[$year->format('Y')][] = $month;
}
}
}
foreach ($months_per_year as $year => $months) {
$january = new Date('01-01-' . $year);
$march = new Date('01-03-' . $year);
$april = new Date('01-04-' . $year);
$june = new Date('01-06-' . $year);
$july = new Date('01-07-' . $year);
$september = new Date('01-09-' . $year);
$october = new Date('01-10-' . $year);
$december = new Date('01-12-' . $year);
if (in_array($january, $months) && in_array($march, $months)) {
$quarter_per_year['label'] = 'T1 / ' . $year;
$quarter_per_year['start_day'] = $january->startOfMonth();
$quarter_per_year['end_day'] = $march->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($april, $months) && in_array($june, $months)) {
$quarter_per_year['label'] = 'T2 / ' . $year;
$quarter_per_year['start_day'] = $april->startOfMonth();
$quarter_per_year['end_day'] = $june->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($july, $months) && in_array($september, $months)) {
$quarter_per_year['label'] = 'T3 / ' . $year;
$quarter_per_year['start_day'] = $july->startOfMonth();
$quarter_per_year['end_day'] = $september->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
if (in_array($october, $months) && in_array($december, $months)) {
$quarter_per_year['label'] = 'T4 / ' . $year;
$quarter_per_year['start_day'] = $october->startOfMonth();
$quarter_per_year['end_day'] = $december->endOfMonth()->endOfDay();
array_push($quarters, $quarter_per_year);
}
}
return $quarters;
}
and getting the years between:
public static function getYearsBetween($start_ts, $end_ts, $full_period = false)
{
$return_data = [];
$current = mktime(0, 0, 0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while ($current < $end_ts) {
$temp_date = $current;
$year = new Date($temp_date);
$return_data[] = $year;
$current = strtotime("+1 year", $current); // add a year
}
if ($full_period) {
$return_data[] = $end_ts;
}
return $return_data;
}
, also getting the months needed
public static function getMonthsBetween($start_ts, $end_ts, $full_period = false)
{
$return_data = $month_list = [];
$current = mktime(0, 0, 0, date('m', $start_ts), date('d', $start_ts), date('Y', $start_ts));
while ($current <= $end_ts) {
$temp_date = $current;
$date = new Date($temp_date);
$month_list[] = $date;
$current = strtotime("+1 month", $current); // add a month
}
$start_date_last_month = new Date(array_first($month_list));
$start_date_last_month = $start_date_last_month->startOfMonth()->format('m-d');
$temp_end_date = new Date($start_ts);
$temp_end_date = $temp_end_date->format('m-d');
if ($start_date_last_month < $temp_end_date) {
array_shift($month_list);
}
$end_date_last_month = new Date(end($month_list));
$current_day_month = $end_date_last_month->endOfMonth()->format('m-d');
$temp_end_date = new Date($end_ts);
$end_day_of_month = $temp_end_date->format('m-d');
if ($end_day_of_month < $current_day_month) {
array_pop($month_list);
}
if (count($month_list) == 0) {
$month_list[] = $end_date_last_month->subMonth();
}
$return_data = $month_list;
if ($full_period) {
$return_data[] = $end_ts;
}
return $return_data;
}
You can do something like in this example:
$February = 2;
$October = 10;
$completedQuarters = ceil($October/3) - ceil($February/3); // = 3
What about the quarter in which the date range starts, should it also count? If it should only count if it begins in the first month of a quarter you can check for it like this:
$completedQuarters = ceil($October/3) - ceil($February/3) -1; // = 2
if($February-1%3 == 0) $completedQuarters += 1;
You´re description is not very clear, let me know if that´s what you had in mind.
Not sure if the following is what you are meaning but might be useful
$date_start='2015/03/12';
$date_end='2017/11/14';
$timezone=new DateTimeZone('Europe/London');
$start=new DateTime( $date_start, $timezone );
$end=new DateTime( $date_end, $timezone );
$difference = $end->diff( $start );
$months = ( ( $difference->format('%y') * 12 ) + $difference->format('%m') );
$quarters = intval( $months / 3 );
printf( 'Quarters between %s and %s is %d covering %d months', $start->format('l, jS F Y'), $end->format('l, jS F Y'), $quarters, $months );
/*
This will output
----------------
Quarters between Thursday, 12th March 2015 and Tuesday, 14th November 2017 is 10 covering 32 months
*/
Something like this in the function and you should be set.
use Carbon\Carbon;
$first = Carbon::parse('2012-1-1'); //first param
$second = Carbon::parse('2014-9-15'); //second param
$fY = $first->year; //2012
$fQ = $first->quarter; //1
$sY = $second->year; //2014
$sQ = $second->quarter; //3
$n = 0; //the number of quarters we have counted
$i = 0; //an iterator we will use to determine if we are in the first year
for ($y=$fY; $y < $sY; $y++, $i++) { //for each year less than the second year (if any)
$s = ($i > 0) ? 1 : $fQ; //determine the starting quarter
for ($q=$s; $q <= 4; $q++) { //for each quarter
$n++; //count it
}
}
if ($sY > $fY) { //if both dates are not in the same year
$n = $n + $sQ; //total is the number of quarters we've counted plus the second quarter value
} else {
for ($q=$fQ; $q <= $sQ; $q++) { //for each quarter between the first quarter and second
$n++; //count it
}
}
print $n; //the value to return (11)
This code is used to take values inputted from a form but this does not take a year entered as 0100 as 0100 but as 1915, this is then used with the JS seen in one of my other questions any help here would be very good, I think the issue is something to do where the year is taken but I just can't get this to work correctly. Is this a limitation of php?
<?php
$year = "";
$month = "";
$day = "";
if (isset($_GET['year']) && !empty($_GET['year'])) {
$year = $_GET['year'];
}
if (isset($_GET['month']) && !empty($_GET['month'])) {
$month = $_GET['month'];
$monthNumber = date('m', strtotime("$month 1 Y"));
}
if (isset($_GET['day']) && !empty($_GET['day'])) {
$day = $_GET['day'];
}
if ($year != "" && $monthNumber != "" && $day != "") {
$fullUrlDate = $year . "-" . $monthNumber . "-" . $day;
$urlDate = new DateTime(date($fullUrlDate));
$today = new DateTime(date("Y-m-d H:i:s"));
$interval = $urlDate->diff($today);
$gapYears = $interval->y;
$gapMonths = $interval->m;
$gapDays = $interval->d;
$gapDaysTotal = $interval->days;
$gapWeeksTotal = round($interval->days/7);
$gapHours = $interval->h;
$gapMinutes = $interval->i;
$gapSeconds = $interval->s;
if ($gapWeeksTotal == 1) {
$gapWeeksSuffix = "";
} else {
$gapWeeksSuffix = "s";
}
if ($gapDays == 1) {
$gapDaysSuffix = "";
} else {
$gapDaysSuffix = "s";
}
$ordinalSuffix = date("S", strtotime($fullUrlDate));
if (strtotime($fullUrlDate) < strtotime(date("Y-m-d H:i:s")) ) {
$dateInThePast = true;
} else {
$dateInThePast = false;
}
// Months gap
$monthsInterval = date_diff($urlDate, $today);
$monthsGap = $monthsInterval->m + ($monthsInterval->y * 12);
$gapMonthsSuffix = ($monthsGap == 1 ? "" : "s");
DateTime has no such limitation, but the date function you use to initialise it, does. You can use DateTime::setDate to set any year you want:
php > $a = new DateTime("2015-08-24");
php > echo $a->format(DateTime::ISO8601);
2015-08-24T00:00:00+0000
php > $a->setDate(90, 8, 24);
php > echo $a->format(DateTime::ISO8601);
0090-08-24T00:00:00+0000
php > $a->setDate(90090, 8, 24);
php > echo $a->format(DateTime::ISO8601);
90090-08-24T00:00:00+0000
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++)
[...]
if(isset($_POST['submit_event'])){
$m = $_POST['event_month'];
$y = $_POST['event_year'];
$d = $_POST['event_day'];
$date = date('Y-n-d',strtotime($y. '-' .$m. '-' .$d));
echo $date;
//i always get 2013-10-07
}
All my inputted datas are correct although the output is always wrong and the same.
if (isset($_POST['submit_event']) && isset($_POST['event_month']) && isset($_POST['event_year']) && isset($_POST['event_day'])) {
$m = $_POST['event_month'];
$y = $_POST['event_year'];
$d = $_POST['event_day'];
$date_pre = $y. '-' .$m. '-' .$d;
$time = strtotime($date_pre)
$date = date('Y-n-d', $time);
echo $date;
}
// For debugging:
else {
echo "Not all variables have been set."
}