Lesson 6 - Conditions in PHP
In the previous exercise, Solved tasks for PHP lesson 5, we've practiced our knowledge from previous lessons.
In the previous lesson, Solved tasks for PHP lesson 5, we talked about forms and created a simple calculator. All it could do is add numbers. In today's lesson, we're going to add to our calculator's functionality with the help of conditions.
Conditions
Conditions (sometimes called branching) allows a script to react to various situations instead of behaving the same every time. For the most part, we only react to user input or events, e.g. when a requested article doesn't exist.
If you have ever programmed in a C-like language, this may be old news to you
We define conditions using the if
keyword which is followed by a
logical expression in parentheses. If the expression is true, the command is
executed. If not, the command is not executed, and the program skips the code in
the if statement and continues.
Let's try it out:
{PHP}
if (15 > 5)
echo('True');
echo('<br />The program continues here...');
{/PHP}
The output would then be:
Operators
We used the >
(greater than) operator in our condition. We
use the following relational operators in expressions overall:
Operator | C-like syntax |
---|---|
Equal to | == |
Greater than | > |
Lower than | < |
Greater than or equal to | >= |
Lower than or equal to | <= |
Not equal to | != |
General negation | ! |
We use two equal signs "=="
to signify equality, and to avoid
having PHP mistake it for a variable assignment for which we do use a single
equals sign. If we want to negate an expression, we put it in parentheses and
prefix it with an exclamation mark. If we want to execute more than a single
command, we put them in a block of curly-brackets. Expressions can contain
variables as well.
Let's try another example:
{PHP}
$a = 10;
$b = 0;
if ($b != 0)
{
$result = $a / $b;
echo("Quotient: $result");
}
if ($b == 0)
echo("You can't divide by zero!");
{/PHP}
The script above will compute and print the quotient of two variables. If the second variable is zero, we'll get an error since we obviously can't divide by zero. If the variables came from the user and we didn't sanitize his/her input, the user could potentially break our application. The security of web applications goes hand in hand with user input sanitation. You'll see just how important it is throughout our courses.
Else
Technically, we've written the condition above twice. The first time in a
regular way, and the second time in the negated way. If it was more complex, we
could've easily made a mistake in the negation. If we wanted something to happen
when a condition is true and something else to happen when it's false, we would
use the else
keyword. The else
(branch) is executed
when a condition is not true:
{PHP}
$a = 10;
$b = 0;
if ($b != 0)
{
$result = $a / $b;
echo("Quotient: $result");
}
else
echo("You can't divide by zero!");
{/PHP}
If there were multiple commands in the else
branch, they would
also have to be in a block of curly brackets.
Else
is also used when we need to manipulate a variable used in
the condition so that we can no longer re-evaluate it. A program remembers that
an expression was false and will execute the else
branch. Let's say
we have a number $a
with a value of 0
or
1
and we want to swap those values (if it is 0
, it
will change to 1
, if it is 1
, it will change to
0
). A naive solution would look something like this:
{PHP}
$a = 0; // we assign 0 into $a
if ($a == 0) // if $a is 0, we assign a value of 1 to it
$a = 1;
if ($a == 1) // if $a is 1, we assign a value of 0 to it
$a = 0;
echo($a);
{/PHP}
It doesn't work, does it? Let's examine what the program does. At the very
beginning, the value assigned to the $a
variable is 0
.
The first condition is true so it sets $a
to 1
. But
then, the second condition becomes true
as well and it sets
$a
back to 0
. If we swap the conditions, the same
thing would happen with 1
. How do we fix this? Oh yeah, using the
else
keyword.
{PHP}
$a = 0; // we assign 0 into $a
if ($a == 0) // if $a is 0, we assign 1 into it
$a = 1;
else // if $a is 1, we assign 0 into it
$a = 0;
echo($a);
{/PHP}
Finally, everything works. There is still a bit more theory on conditions that we didn't cover, but it can wait until the next lesson. Now, let's update our calculator using what we went over today.
Improving the calculator
Let's start with the HTML form where the user chooses the operation. We'll add a select tag through which we'll choose which operation we want to use. For the sake of completeness, I'll show you the entire HTML file:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Calculator</title> </head> <body> <p>Welcome to the calculator, please insert 2 numbers and choose operation</p> <form method="POST" action="compute.php"> <input name="number1" type="text" /><br /> <input name="number2" type="text" /><br /> Operation: <select name="operation"> <option value="sum">Sum</option> <option value="subtraction">Subtraction</option> <option value="multiplication">Multiplication</option> <option value="division">Division</option> </select><br /> <input type="submit" value="Compute" /> </form> </body> </html>
The result will be as follows:
When the form is submitted, we'll receive the operation chosen by the user in
$_POST['operation']
.
Let's move to the processing script which used to be sum.php
.
Since the script name doesn't correspond with what it does anymore, I renamed it
compute.php
. Now let's add a bit of branching there to sanitize the
user input.
To make the code clearer, we'll assign the values from the POST
array to new variables. This allows us to use them without having to write
$_POST
every time, which will make our code much more readable.
$a = $_POST['number1']; $b = $_POST['number2']; $operation = $_POST['operation'];
After that, we'll insert a condition for choosing the operation. Since it's
not really necessary to evaluate the other conditions when some of them are
true, we'll use an if
... else if
..." sequence:
if ($operation == 'sum') $result = $a + $b; else if ($operation == 'subtraction') $result = $a - $b; else if ($operation == 'multiplication') $result = $a * $b; else if ($operation == 'division') { if ($b != 0) $result = $a / $b; else $result = 'Error'; } echo("Result: $result");
You may also encounter else if
written as a single keyword, i.e.
elseif
. If the operation is the sum, the other conditions won't be
evaluated because the condition was true. The program would then skip right to
printing the result. In other words, the only conditions are only evaluated up
until the point where one is true within that logic level.
I looking forward to seeing you all in the next lesson, Solved tasks for PHP lesson 6, where we'll finish up on conditions. The code we worked on today is available of download below the article, as usual.
In the following exercise, Solved tasks for PHP lesson 6, we're gonna practice our knowledge from previous lessons.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 49x (1.69 kB)
Application includes source codes in language PHP