Saad Bashir
Saad Bashir

Reputation: 4519

PHP - If () Condition

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?

Upvotes: 0

Views: 10907

Answers (4)

dejjub-AIS
dejjub-AIS

Reputation: 1541

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";
 }
?>

Upvotes: 1

Richard J. Ross III
Richard J. Ross III

Reputation: 55543

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.

Upvotes: 2

undone
undone

Reputation: 7888

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

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

Upvotes: 0

xdazz
xdazz

Reputation: 160833

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

Upvotes: 1

Related Questions