0

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?

dejjub-AIS
  • 1,501
  • 2
  • 24
  • 50
Saad Bashir
  • 4,341
  • 8
  • 30
  • 60

4 Answers4

2

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.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • I am a little confused. For an if statement with AND shouldn't both conditions be true? if ($tdate != "Sat" && $tdate != "Sun") {} < means its not Sat & not Sunday right? And if ($tdate != "Sat" || $tdate != "Sun") { } < means if it is not Saturday, check the second condition and if it is not Sunday then run the what is in the brackets. But if it is Saturday, then skip this if function. I am a bit confused here. Reply to this query should help me clear this confusion. Thanks! – Saad Bashir Mar 03 '12 at 05:30
  • Basically, you are checking in this snippet if the day is NOT a weekend. To check if it IS a weekend, you would use `==` with `||`, instead of `!=` with `&&` – Richard J. Ross III Mar 03 '12 at 08:21
  • if it still confuses you, better draw a [truth table](http://en.wikipedia.org/wiki/Truth_table) and check how it behaves – dejjub-AIS Mar 03 '12 at 08:23
1
if ($tdate != "Sat" && $tdate != "Sun") {
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

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";
 }
?>
dejjub-AIS
  • 1,501
  • 2
  • 24
  • 50
0
 if ($tdate != "Sat" || $tdate != "Sun")

when it's Sat, So it's not Sun and condition of if is true.use && instead.

undone
  • 7,857
  • 4
  • 44
  • 69