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?

2
  • You just need to change your OR (||) to an AND (&&) =p Commented Mar 3, 2012 at 5:11
  • 2
    See this answer for a much simpler idea: stackoverflow.com/a/4802362/362536 Commented Mar 3, 2012 at 5:12

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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!
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 &&
if it still confuses you, better draw a truth table and check how it behaves
1
if ($tdate != "Sat" && $tdate != "Sun") {

2 Comments

You don't explain the problem, you just show the solution. IMO, a bad answer, so I downvoted.
@RichardJ.RossIII This isn't necessary to explain, just a miss for op perhaps.
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";
 }
?>

Comments

0
 if ($tdate != "Sat" || $tdate != "Sun")

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.