PHP - If () Condition - php

I need to check if the day today is Saturday or Sunday. And i am trying to use simple if function for that but I don't know why it doesn't seem to work.
<?php
$tdate = date("D");
echo "Today is $tdate - ";
if ($tdate != "Sat" || $tdate != "Sun") {
echo "Weekday";
}
else {
echo "Weekend: $tdate";
}
?>
And the output I am getting is as follows:
Today is Sat - Weekday
What is exactly wrong with the if function?

You are performing a OR, which checks if one or the other statements are true. This means that while $tdate != "Sat" is false, $tdate != "Sun" is true. If you simply change your OR (||) to an AND (&&), your code will work fine.

if ($tdate != "Sat" && $tdate != "Sun") {

Its a logical error you need to fix
What you are saying is
If "today is NOT Saturday" OR "today is NOT Sunday", then its a Weekday
So yields TRUE because, one of the two conditions has satisfied (when the day is either Saturday or Sunday) and it goes into the true block and prints as weekday
The fix can be in two ways, 1st what xdazz gave OR the one below
<?php
$tdate = date("D");
echo "Today is $tdate - ";
if (!($tdate == "Sat" || $tdate == "Sun")) {
echo "Weekday";
}
else {
echo "Weekend: $tdate";
}
?>

if ($tdate != "Sat" || $tdate != "Sun")
when it's Sat, So it's not Sun and condition of if is true.use && instead.

Related

Conditional based on day of week and time range

I'm trying to find a solution to a conditional based on the day of the week and a time range within that day. I've managed to hunt down the code for the day of the week but I can't find how to incorporate a time frame within the day?
For example:
IF today is Monday AND between 2pm and 4pm THEN do THIS
This is what I have...
<?php
date_default_timezone_set('Australia/Perth'); // PHP supported timezone
$script_tz = date_default_timezone_get();
// get current day:
$currentday = date('l'); ?>
<?php if ($currentday == Monday){ ?>
Monday
<?php } elseif ($currentday == Tuesday){ ?>
Tuesday
<?php } elseif ($currentday == Wednesday){ ?>
Wednesday
<?php } elseif ($currentday == Thursday){ ?>
Thursday
<?php } elseif ($currentday == Friday){ ?>
Friday
<?php } elseif ($currentday == Saturday){ ?>
Saturday
<?php } elseif ($currentday == Sunday){ ?>
Sunday
<?php } else { ?>
<?php } ?>
I'm not sure if this may help for the time frame?
Check day of week and time
Basically this:
<?php
if (date('l') === 'Monday' && date('G') >= 2 && date('G') < 4) {
// do something
}
You were missing quotes around the day names.
The condition I wrote will evaluate to true on Monday between 2 PM and 4 PM (while 4 PM itself will not, e.g. the last allowed values is 3:59 PM).
you could use different date/time components to streamline the code:
function between($value, $start, $end)
{
return $value > $start && $value <= $end;
}
$hours = date("G");
switch( date("N"))
{
case 1: //monday
if (between($hours,12 + 2,12 + 4 )) //using 24h format to avoid checking am/pm
{
// IF today is Monday AND between 2pm and 4pm THEN do THIS
}
break;
case 2: //tuesday
break;
//....
}
You'd better user date('N') as it is not language dependant and date('H') to take advantage of the 24h format that is better fit for time comparison.
function date_in_frame($test_date, $day, $start, $end){
$d = new Datetime($test_date);
return $d->format("N") == $day && $d->format("H") >= $start && $d->format("H") < $end;
}
//test if "now" is Monday between 2pm (14:00) and 4pm (15:59)
var_dump(date_in_frame("now", 0, 14, 16));
This code here checks a DateTime is between a start and end time.
<?php
$date = new DateTime('2019-11-18 12:49');
$start = new DateTime('2019-11-18 09:00');
$end = new DateTime('2019-11-18 17:00');
if ($date > $start && $date < $end) {
echo 'In the zone!';
}
Note.
$date->format('l'); will return Monday or whatever day it is.
$date->format('H:i'); will return 13:15 or whatever time it is.
Have a play! https://3v4l.org/XK5KR
All the conditions packed into an array is easier for maintenance.
A simplified example:
$ranges = [
['Monday',12,14, function(){echo "do something";}],
['Tuesday',12,14, function(){echo "do something on Tue";}],
//: more
];
$curWeekDay = date('l');
$hours = date("G");
foreach($ranges as $range){
if($curWeekDay == $range[0] AND $hours >= $range[1] AND $hours < $range[2]){
$range[3]();
}
}
Output on Tue 13:25:
do something on Tue

Running code between certain times

I have php code that is suppose to run between 04:00am and 05:00am but it does not run, i cant see the problem with this?
$begin = new DateTime('04:30');
$end = new DateTime('05:00');
while (!connection_aborted() || PHP_SAPI == "cli") {
$now = new DateTime();
if(date("Hi") <= $begin && date("Hi") >= $end){
//run code
}
}
Your problem lies here:
if(date("Hi") <= $begin && date("Hi") >= $end){
You are trying to do "greater than" and "less than" comparisons on strings. You should use the integer values (epoch time) then you can do this.
if(time() >= strtotime('14:00') && time() <= strtotime('15:00')) {
echo 'In Range2';
} else {
echo 'out of range2';
}
Note: This is for between 2:00pm and 3:00pm just to show it works (it currently is 2:00pm where I am located).
Demo: https://3v4l.org/NhnfM

Simple PHP If Statement Not Acting As Expected

This is a simple year validation that should check if the year is between 1900 and the current year. If the year is valid it should be displayed as the input's value.
if(!empty($year) && $year >= 1900 || !empty($year) && $year <= date('Y')){
$yearHolder = 'value="'.$year.'"';
}else{
$yearHolder = 'placeholder="Year"';
}
The problem I'm having is that the statement does not work, and passes any numbers through.
You can try this.
if(!empty($year) && $year >= 1900 && $year <= date('Y')){
$yearHolder = 'value="'.$year.'"';
}else{
$yearHolder = 'placeholder="Year"';
}
To be sure about conditions, place it separately.
if(!empty($year))
{
if ($year >= 1900 && $year <= date('Y'))
{
$yearHolder = 'value="'.$year.'"';
}else{
$yearHolder = 'placeholder="Year"';
}
} else {
echo "Year is empty";
}
You have to change your middle || OR condition to and AND condition, to get your logic, which you want. Right now in other words your condition is:
IF $year is NOT empty AND $year is either bigger than 1900 OR less than 2015
But what you want is:
IF $year is NOT empty AND $year is either bigger than 1900 AND less than 2015
So your if statement should look something like this:
if(!empty($year) && $year >= 1900 && $year <= date("Y"))
Also note, that the function call date() is at the end, which makes it only execute, if the other two pieces in the condition are TRUE. That is because PHP has short circuit evaluation.
Consolidating other suggestions, you could try something like this:
if (!empty($year) && $year >= 1900 && $year <= date('Y')) {
$yearHolder = 'value="' . $year . '"';
} else {
$yearHolder = 'placeholder="Year"';
}
This removes the redundant check for empty values, corrects your || to an &&
Try:
if(!empty($year) && $year >= 1900 && $year <= date('Y')){
No need to check if $year is empty twice and make them all ANDs.

Test variable against array in PHP

Im thinking I should be using in_array() but for some reason it is giving me inaccurate information. I looked through the array_search() and array_key_exists() but it looks like that is only helpful if I have a key and value in my array which I dont. In a nutshell Im running a condition to get the current EST time and day and determine if it is "during hours" or "after hours".
So it is 19:00 on Tuesday, this should say "After Hours" but it is echoing "During Hours", am I missing something?
Sample code:
<?php
date_default_timezone_set('US/Eastern');
$current_time = date('A'); //AM or PM
$current_day = date('l'); // Sunday - Saturday
$current_hour = date('H'); // 08 / 24hr Time Format
$closed_days = array('Saturday','Sunday');
$closed_hours = array('17','18','19','20','21','22','23','00','01','02','03','04','05','06','07','08');
?>
<?php
echo $current_time . '<br />';
echo $current_day . '<br />';
echo $current_hour . '<br />';
//Operating Hours
if(!in_array($current_day, $closed_days) || !in_array($current_hour, $closed_hours)) {
echo 'During Hours';
} else {
echo 'After Hours';
} ?>
Is returning:
PM
Tuesday
19
During Hours
Change:
if(!in_array($current_day, $closed_days) || !in_array($current_hour, $closed_hours)) {
to
if(!in_array($current_day, $closed_days) && !in_array($current_hour, $closed_hours)) {
The || equates to "or" so the condition was returning true say it was an off day but during your normal hours
Using && equates to "and" which requires both conditional statements to be true to execute the code block
I'm pretty sure it is as simple as changing your if statement from:
!in_array($current_day, $closed_days) || !in_array($current_hour, $closed_hours)
To:
!in_array($current_day, $closed_days) && !in_array($current_hour, $closed_hours)
By using OR, you are saying only 1 condition has to be true
Change
if(!in_array($current_day, $closed_days) || !in_array($current_hour, $closed_hours)) {
echo 'During Hours';
} else {
echo 'After Hours';
}
to
if(in_array($current_day, $closed_days) || in_array($current_hour, $closed_hours)){
echo 'After Hours';
}
else{
echo 'During Hours';
}

Show a message at specific times on a specific day

How can I insert a specific minute into the following to show a message:
if ($current_day == "Monday") {
if ($current_time >= 15 && $current_time <= 16) {
echo "message";
}
}
For example I want "message" to show at 3:45 or 15:45 and not between the 15th and 16th hour.
I figured out how to do it with javascript:
// Sunday is 0 Monday is 1 and so on
// January is 0 February is 1 and so on
var Digital=new Date()
var month=Digital.getUTCMonth()
var day=Digital.getUTCDate()
var year=Digital.getUTCFullYear()
var hours=Digital.getUTCHours()
var minutes=Digital.getUTCMinutes()
if (month==2&&day==16&&year==2015&&hours==01&&minutes==30 || hours==01&&minutes==45 || hours==01&&minutes==47)
document.write('<b>message here</b>')
else if (month==2&&day==17&&year==2015&&hours==01&&minutes==30 || hours==01&&minutes==45 || hours==01&&minutes==47)
document.write('<b>message 2 here</b>')
else
document.write('<b></b>')
Works perfectly no matter what timezone you're in. There's probably a less crazy way to do this but this is what I have so far.
In order to show a message at exactly 3:45 AM and again at 3:45 PM, you could try this:
$current_day = date('l');
$current_time = date('G:i');
if ($current_day == "Monday") {
if ($current_time == '03:45' || $current_time == '15:45') {
echo "message";
}
}
Or a little cleaner way (especially if you wanted to include a longer list of times):
if (date('l') == "Monday") {
if (in_array(date('G:i'), array('03:45','15:45')) {
echo "message";
}
}
EDIT: To specify a timezone, try inserting this line before either of the above pieces of code:
date_default_timezone_set('America/Los_Angeles');
Where 'America/Los_Angeles' could be any supported string representing your desired timezone from this page of the PHP manual: http://php.net/manual/en/timezones.php

Categories