If/Else Statements
       by kirupa : 27 June 2004

In the previous page we covered the basic structure of if and else statements. This page will cover in greater detail various modifications for the if and else statements.

Conditional Operators
All of this time I have been using conditional operators such as == to determine whether a condition is true or not. But I never elaborated on what the various conditional operators are, and how they can be used to see if something is true or not. I think now is a good time to explain that.

The following table lists the more popular conditional operators you can use in PHP:

Operator Description
== Equals
>= Greater than or Equal
<= Less than or Equal
> Greater than
< Less than
!= Not Equal

An example using something other than the equals conditional operator could be:

<?php
$num = 5;
if ($num > 4) {
print("Number greater than 4.");
}
?>

In the preceding example we used the greater than ( > ) operator that compares whether the variable $num is greater than 4. Since 5 is greater than 4, the statement is true, and the code will be executed.

If you were to replace the greater than operator ( > ) in the above code with the not equal  ( != )operator, the code will be true also. 5 does not equal 4, and that is true!


Logical Operators
Throughout this tutorial, our If statements depended on only one condition. If that one condition was true, the code would executed. Let's introduce logical operators that will allow you to set multiple conditions.

The operators that you will use frequently is AND and OR.

 
Operator Description
&& And
|| Or
and And
or Or

Here is a PHP example using one of the logical operators:

<?php
$username = admin;
$password = password;
if (($username == admin) && ($password == password)) {
print("Access granted!");
}
?>

The first condition checks to make sure that $username equals admin. The second condition checks to make sure that $password equals password. The logical operator && checks to see if both condition statements are true.

If your value for password changed, the condition would fail. Even though one condition is true, because the && logical operator needs BOTH conditions to be true, the test fails. If you used the || operator, all you would need is for one condition to be true. Needless to say, if both conditions fail, && and || will not help make your statements true.

I hope the information helped. If you have any questions or comments, please don't hesitate to post them on the kirupa.com Forums. Just post your question and I, or our friendly forum helpers, will help answer it.

The following is a list of related tutorial and help resources that you may find useful:

How to use the Forums
New, Upcoming, and In-Progress Tutorials
How to Help out kirupa.com
Writing Tutorials
 
Cheers!
Kirupa Chinnathambi
kirupaBlog

 


page 2 of 2

 

 




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.