PHP Conditional Statements

Conditional statements are used to allow the program to execute different program statements (or blocks of program statements) depending on the state (condition) of one or more program variables. Like the C programming language, PHP has a number of conditional statements, which are described below.

The following program demonstrates how some of these conditional statements might be used:



  // First, a couple of simple if statements.

  if ($day =="Sat" or $day == "Sun")
    echo "It’s the weekend!";
  if ($day !="Sat" and $day != "Sun")
    echo "Today is a weekday.";

  // An if … else statement can do the same kind of thing more efficiently.

  if ($day =="Sat" or $day == "Sun")
    echo "<br><br>I hope you are having a nice weekend.";
    echo "<br><br>It is not the weekend yet.";

  echo "<br><br>Today is ";

  // An if … elseif … else statement can test for several possible conditions.

  if ($day =="Mon")
    echo "Monday.";
  elseif ($day =="Tue")
    echo "Tuesday.";
  elseif ($day =="Wed")
    echo "Wednesday.";
  elseif ($day =="Thu")
    echo "Thursday.";
  elseif ($day =="Fri")
    echo "Friday.";
  elseif ($day =="Sat")
    echo "Saturday.";
    echo "Sunday.";

  // A switch statement can also test for several possible conditions.
  // Switch statements are preferred if there are a significant number
  // of different possible outcomes. You can also specify a default action
  // (code to be executed if none of the other conditions is true).

  switch ($day)
    case "Mon":
      echo "<br><br>I hate Mondays!";
    case "Tue":
      echo "<br><br>The weekend seems a long way off.";
    case "Wed":
      echo "<br><br>Half way through the week!";
    case "Thu":
      echo "<br><br>One more day before the weekend.";
    case "Fri":
      echo "<br><br>Nearly the weekend!";
    case "Sat":
      echo "<br><br>I like Saturdays.";
      echo "<br><br>Sunday is usually a quiet day.";

Note that the default action is used here simply to demonstrate how it works. If $day is "Sun" (i.e. not any of the other cases), the default action will occur, namely to echo the text "Sunday is usually a quiet day." to the screen. Enter the code above into a text editor and save it with the filename "conditional.php" in the "htdocs" directory of your "xampp" directory. Run the XAMPP server, then type the following URL into the browser's address bar:


You should see output that is something like the screenshot below (the text displayed will, of course, be dependent on the day of the week).

The output from conditional.php

The output from conditional.php