Lesson 6: Conditions
Ak Patel
---
If...
The first type of condition we will look at is if (condition) {
statement
}
<html> <head> <title>Loops </title> </head> <body> <?php $x = 2; if ($x > 1) { echo "<p>variable $x is greater than 1 </p>"; } ?> </body> </html>
if ... else ...
The next type of condition will want to look at is
if (condition) {
statement
}
else {
statement
}
In lesson 4, you learned how to find the number of a month. In the following example, we will use the month number in an
<html> <head> <title>Conditions</title> </head> <body> <?php if (date ("m") == 3) { echo "<p>Now it's spring!</p> "; } else { echo "<p>I do not know what season it is!</p> "; } ?> </body> </html>
However, there are plenty of ways to improve the condition and make it more precise. Below are listed comparison operators that can be used in the condition:
== Equals
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
In addition, there are some logical operators:
&& And
|| Or
! Not
The operators can be used to develop more precise conditions, so now we can expand the above example to include all the spring months:
<html> <head> <title>Conditions</title> </head> <body> <?php if (date("m") >= 3 && date("m") <= 5) { echo "<p> Now it's spring!</p> "; } else { echo "<p> Now it's either winter, summer or autumn!</p> "; } ?> </body> </html>
date("m") >= 3 && date("m") <= 5
If the month is greater than or equal to 3, and the month is less than or equal to 5
But it still only works with March, April and May. All other months are not yet covered by the condition. So let's try to develop the condition a little more.
if ... elseif ... else...
Using<html> <head> <title>Conditions</title> </head> <body> <?php if (date("m") >= 3 && date("m") <= 5) { echo "<p>Now it's spring!</p>"; } elseif (date("m") >= 6 && date("m") <= 8) { echo "<p>Now it's summer!</p>"; } elseif (date("m") >= 9 && date("m") <= 11) { echo "<p>Now it's autumn!</p>"; } else { echo "<p>Now is winter!</p>"; } ?> </body> </html>
switch ... case
Another way of writing conditions is to use the switch (expression) {
case 1:
statement
break;
case 2:
statement
break;
default:
statement
break;
}
As you may remember from lesson 4, the function
<html> <head> <title>Conditions</title> </head> <body> <?php switch(date("w")) { case 1: echo "Now it's Monday"; break; case 2: echo "Now it's Tuesday"; break; case 3: echo "Now it's Wednesday"; break; case 4: echo "Now it's Thursday"; break; case 5: echo "Now it's Friday"; break; case 6: echo "Now it's Saturday"; break; default: echo "Now it's Sunday"; break; } ?> </body> </html>
Often