Lesson 7 - More on Conditions in PHP - Casting, composing, and switches
In the previous exercise, Solved tasks for PHP lesson 6, we've practiced our knowledge from previous lessons.
In the previous lesson, Solved tasks for PHP lesson 6, we introduced you to conditions and
if
- else
commands. We also talked about relational
operators and improved our calculator. There is some more stuff we have to cover
about conditions, or else you'd be missing out on a lot. Let's get right into
it!
The boolean
data type
The boolean
data type goes hand in hand with conditions.
Variables of this type can only contain two values - true
or
false
. At times, you may encounter those keywords written in
uppercase. Let's go ahead and create a boolean
variable:
{PHP}
$greet = true;
if ($greet == true)
echo('Hello');
{/PHP}
The code above checks whether the $greet
variable holds a value
of "true"
. If it does, it prints out a greeting. The
true
and false
values are often used for application
settings.
If we go a bit deeper into relational operators, they always return a
boolean
result (e.g. 5 > 2
returns
true
). A condition only has two states, it can be true or it can be
false. We can insert a boolean
variable directly as condition
without an operator:
{PHP}
$greet = true;
if ($greet)
echo('Hello');
{/PHP}
Some of you all may be wondering, is there a way to store the expression
result into a boolean
variable that we could use later? You guessed
it!
$condition = (15 > 3); if ($condition) { // ... }
Comparing and type casting
We already know that the "=="
operator is used when comparing 2
values. We also know that PHP is a dynamic language and that a variable's data
type is automatically converted depending on how we use them. This is referred
to as type casting and is also performed when using conditions.
It's really important for you to know how it works. Otherwise, PHP may pull a
quick one on you, and may even result in security vulnerabilities in your
applications.
Casting to boolean
If we use a variable of any type as a condition, it'll be automatically cast
to boolean
(meaning to true or false). If we use any
non-zero number as an expression, it'll be always evaluated as
true, even for negative numbers, and the condition will be executed:
{PHP}
$a = 5;
if ($a)
echo("The condition is true.");
{/PHP}
Condition would also be true for strings with a length that is greater than zero:
{PHP}
$s = 'ict.social';
if ($s)
echo("The condition is true.");
{/PHP}
They work in a similar way with arrays. If the array contains anything at all, the condition will be true:
{PHP}
$numbers = array(1, 2, 3);
if ($numbers)
echo("The condition is true.");
{/PHP}
This is a very useful tool for any and every programmer. Especially when the
number in the condition is what is known as a "counter". A very common
expression when it comes to counters is "> 0"
(greater than
zero). It works with it kind of like it would with an array. The entire
expression would look something like this "count($numbers) > 0"
.
A string would only meet the condition if it is not empty. This way, we can
check whether the user filled a field in a form.
We could also set up conditions in a negated way, like this:
{PHP}
$name = '';
if (!$name)
echo("Your name can't be empty!");
{/PHP}
Comparing variables of different data types
Things gets interesting when PHP implicitly (automatically) casts data types during value comparisons (most commonly with numbers and strings).
As some of you may have guessed, when we compare a number to itself as a string, the condition will be true:
{PHP}
$a = 2;
$b = "2";
if ($a == $b)
echo("Variables are equal!");
{/PHP}
PHP finds out that there is a number on the left side of the condition and tries to convert the right side of the condition to a number as well. In this case, it will succeed in doing so. When it comes down to it, we're comparing two number twos, which is undoubtedly equal.
You surely remember that PHP is very active in performing type-casts and tries to convert types whenever it's at least even the slightest bit possible. The following condition is also true, even thought it might be seemingly unlikely:
{PHP}
$a = 2;
$b = "2Hey, how are you?";
if ($a == $b)
echo("The variables are equal!");
{/PHP}
PHP separates the number 2 from the string and compares two twos. This only works when a string begins with a number.
Now, let's take a look at a result that will come unexpected to many of you. This condition is true:
{PHP}
$a = 0;
$b = "Hey, how are you?";
if ($a == $b)
echo("The variables are equal!");
{/PHP}
How can it be, you say? PHP knows that we want to compare a number to some
other thing, so it converts the string to a number. When it fails to do so,
instead of an error message, it returns a result of 0
. Then, as you
all know, zero equals zero
Strict comparisons
If the last example seems a bit wild to you, you're absolutely right. It's
best to stick to comparing strictly to a single data type. Especially when it
comes to strings. If we use ===
instead of ==
, an
expression will only be true
if the values are truly the same and
are of the same data type.
{PHP}
$a = 0;
$b = "Hey, how are you?";
if ($a === $b)
echo("They are equal!");
{/PHP}
The condition would no longer apply. The same goes for a number and a string:
{PHP}
$a = 2;
$b = "2";
if ($a === $b)
echo("They are equal!");
{/PHP}
I highly recommend comparing strings using ===
.
Composing conditions
Conditions can be structured properly with the help of two logical operators:
Operator | C-like syntax |
---|---|
And | && |
Or | || |
Let's set up an example, we'll check whether a given number is between
10-20
:
{PHP}
$a = 15;
if (($a >= 10) && ($a <= 20))
echo("Correct!");
else
echo("You did it wrong");
{/PHP}
This way, we could validate the age entered by the user on a form. You should
all be able to wrap your head around things like that now. Operators can also be
combined using parentheses. Let's check whether the number is between
10-20
or 30-40
:
{PHP}
$a = 35;
if ((($a >= 10) && ($a <= 20)) || (($a >=30) && ($a <= 40)))
echo("Correct!");
else
echo("You did it wrong");
{/PHP}
Switch
To finish up with conditions, we'll go over switch
constructs.
Technically, all a switch construct is, is an alternative way of writing an
if
...else
... sequence. Switch
es allow for
us to react to various values that a variable might hold. Let's take a quick
look at our calculator script. However, this time, we'll use a
switch
instead of the if
...else
...
sequence:
switch ($operation) { case 'sum': $result = $a + $b; break; case 'subtraction': $result = $a - $b; break; case 'multiplication': $result = $a * $b; break; case 'division': if ($b != 0) $result = $a / $b; else $result = 'Error'; break; } echo("Result: $result");
The switch
keyword is followed by the parentheses that contain
the variable to which cases react to. The switch
body is inside of
a block of curly brackets. Each value (case
) is marked with the
case
keyword followed by a colon. After that, we simply write the
commands that we want to be executed. Here, we don't have to add a block of
curly brackets if we want to enter multiple commands. However, the final command
in a case has to be followed by the break
keyword. We can also use
the default
case: which will be executed when the variable didn't
meet any of the cases.
Personally, I don't use switch
es very much. I don't think that
it's any more readable than if...else... sequences and good programmers don't
use them very often. Long branching should be avoided overall since there are
shorter and more elegant ways to solve anything and everything (e.g. with
polymorphism, reflection or using anonymous functions, which we will get to
later on ). You will surely
encounter switch
es in other programmers' code, so I thought I would
at least mention them. In the next lesson, E-mail form in PHP, we'll get into some more
hands-on stuff. This time, it will be an e-mail form.