|
[php home]
Php_5: Using Conditionals and Operators
Comparison Operators:
|
==
|
equal to |
|
<
|
less than |
|
>
|
greater than |
|
<=
|
less than or equal to |
|
>=
|
greater than or equal to |
|
!=
|
not equal to |
Remember that a single equal sign ( = ) means that you are assigning
a value to a variable. $num = 10;
The basic if clause:
if (condition) {
// Do something
} |
if (condition) {
// Do something
} else {
// Do something else
} |
if (condition1) {
// Do something
} elseif (condition2) {
// Do something else
} else {
// Do something else
} |
Set up the following Example: If we would set up a form asking
a person if they use a Windows based machine or a Mac, there could be
three possible results. The person could choose "pc", "mac"
or not make a selection. Using an if clause, we can return a message based
on their response.
HTML FORM:
<form action="php_5.php" method="post">
<INPUT TYPE="radio" NAME="platform" VALUE="mac">mac<br>
<INPUT TYPE="radio" NAME="platform" VALUE="pc">pc
<input type="submit"> <input type="reset">
</form>
PHP:
<?php
if ($_POST['platform'] == "pc") {
echo "to fix the problem on a PC, try... ";
} elseif ($_POST['platform'] == "mac") {
echo "to fix the problem on a MAC, try ...";
} else {
echo "Please select which platform you are using";
}
?>
NOTE: Notice the use of the single and
double equal sign. One equal sign means that the variable is assigned
or gets that value. Two double quotes is asking if something has the same
value. If $platform == (is the same as) "pc", then the statement
is true, if not PHP will move on to the next condition.
NOTE: If a condition is true, the code
inside the { } will be executed. If not, PHP will continue on until it
finds a true statement or until it gets to the else statement. Make sure
that your else statement is always last. The elseif can also be written
as else if (two words).
Exercise 5.1: Using the above example, set up
a page that asks a student if he/she is a
freshman, sophomore, junior or senior.
|