Lesson 6 - Conditions in PHP

PHP Basic constructs Conditions in PHP

In the previous lesson, Associative arrays in PHP and submitting forms, 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:

if (15 > 5)
        echo('True');
echo('<br />The program continues here...');

The output would then be:

Your page
localhost

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:

$a = 10;
$b = 0;
if ($b != 0)
{
        $result = $a / $b;
        echo("Quotient: $result");
}
if ($b == 0)
        echo("You can't divide by zero!");

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:

$a = 10;
$b = 0;
if ($b != 0)
{
        $result = $a / $b;
        echo("Quotient: $result");
}
else
        echo("You can't divide by zero!");

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:

$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);

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.

$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);

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:

Calculator
localhost/cal­culator/calcu­lator.html

When the form is submitted, we'll receive the operation chosen by the user in $_POST['opera­tion'].

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, More on Conditions in PHP - Casting, composing, and switches, where we'll finish up on conditions. The code we worked on today is available of download below the article, as usual.


 

Download

Downloaded 44x (1.69 kB)
Application includes source codes in language PHP

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
All articles in this section
PHP basic constructs
Activities (9)

 

 

Comments

Avatar
Tabish Ali
Member
Avatar
Tabish Ali:2/7/2017 2:29

Here i modified this code , now result is displayed in same page and i used some bootstrap classes for good looking. :-D

<!DOCTYPE>
<html lang="en-US">
<head>

<meta charset="utf-8">
<title>Calcula­tor</title>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https:/­/maxcdn.bootstrap­cdn.com/bootstrap/3­.3.7/css/boot­strap.min.css">

<!-- jQuery library -->
<script src="https://­ajax.googleapis­.com/ajax/lib­s/jquery/3.1.1/jqu­ery.min.js"></scrip­t>

<!-- Latest compiled JavaScript -->
<script src="https://­maxcdn.bootstrap­cdn.com/bootstrap/3­.3.7/js/bootstrap­.min.js"></scrip­t> </head>
<!----------------------------------------------------------------------------------------------------------->

<body>
<div class="container">
<form method="post" action="<?php echo htmlspecialchar­s($_SERVER["PHP_SEL­F"]);?> " role="form" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2">Number 1 :</label>
<div class="col-sm-4">
<input placeholder="Number-1" class="form-control" name="num1"></­input>
</div>
</div>

<div class="form-group">
<label class="control-label col-sm-2">Number 2 :</label>
<div class="col-sm-4">
<input placeholder="Number-2" class="form-control" name="num2"></­input>
</div>
</div>

<div class="form-group">
<label class="control-label col-sm-2">Operation :</label>

<div class="col-sm-2">

<select class="form-control" name="oper">
<option value="sum">Sum<­/option>
<option value="sub">Sub­traction</opti­on>
<option value="mul">Mul­tiplication</op­tion>
<option value="div">Di­vision</option>

</select>

</div>

</div>

<div class="form-group">
<div class="col-sm-2 col-sm-offset-2">

<button value="submit" name="submit" type="submit" class="btn btn-success">Compu­te</button>

</div>
</div>

</form>
</div>

<?php

$a = $b = $op = "";

if ($_SERVER["RE­QUEST_METHOD"] == "POST"){

$a = $_POST['num1'];
$b = $_POST['num2'];
$op = $_POST['oper'];

if ($op == 'sum')
$result = $a + $b;

else if ($op == 'sub')
$result = $a - $b;

else if ($op == 'div')
{
if ($b != 0){
$result = $a / $b;}
else
$result = 'Infinity';

}
else if ($op == 'mul')
$result = $a * $b;

echo '<div class="container" > <div class= "alert alert-success alert-dismissible">
×Answer: ' .
"$result
</div></div>";

}
?>

</body>
</html>

Reply  +1 2/7/2017 2:29
there is no limit to learn.
Avatar
Justin Jake Telo:4. February 22:41

how about use curly braces in the end of condition?

if ($a == 0){
echo "blah blah blag";
}
else if {
echo "blah blah nah";
}
else {
echo "nanana";
}

//something like this

Edited 4. February 22:41
 
Reply 4. February 22:41
Avatar
IT Man
Member
Avatar
Replies to Justin Jake Telo
IT Man:5. February 1:40

You can if you want to. It won't change the meaning. :)

Reply 5. February 1:40
Don't be silly and smile!
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

3 messages from 3 displayed.