So-called control structures allow us to decide which parts of our code are executed depending on whether one or more conditions are met or not.
If a user wants to log into a service, but the username or password
does not match, an error message will be displayed.
Otherwise, access will be granted.
If the balance of a bank account is greater than 0, allow a withdrawal.
Otherwise, display a message saying that there are insufficient funds.
Comparison Operators
To be able to verify, whether conditions are met or not (true or false) we need special operators for comparison. The most common ones allow you to check, if one value in comparison to another value is:
>
greater than<
less than==
equal to!=
not equal to>=
greater than or equal to<=
less than or equal to
Comparisons like that are also called expressions and they return
either true
or false
. Let's look at a few examples.
var_dump("Hello" == "Good bye");
var_dump(1 > 2);
var_dump(1 <= 2);
var_dump(1 != 1);
var_dump(1 == 1);
bool(false)
bool(false)
bool(true)
bool(false)
bool(true)
Apart from those, we have an additional operator to check
if not just the value but also the type are equal and it looks like this ===
.
And of course, it's counterpart !==
to check if they are not identical.
var_dump(0 == 0.0);
var_dump(0 === 0.0);
var_dump(0 !== 0.0);
var_dump(0 == '');
var_dump(0 === '');
var_dump(0 !== '');
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
The if Statement
The if statement is by far the most frequently used one.
We check if something is true and do something. The basic
syntax looks like so if (expression) { do something }
.
// check within the if block
if (1 < 2) {
echo "1 is less than 2\n";
}
// and this works as well
$isUserLoggedIn = true;
if ($isUserLoggedIn) {
echo "Yay - you are logged in!\n";
}
1 is less than 2
Yay - you are logged in!
Since the variable already holds a boolean value, there's no need to do
something like ($isUserLoggedIn == true)
. That would be redundant,
because $isUserLoggedIn itself is true. This can also be reversed with an
exclamation mark !
to check if something is false.
$isUserLoggedIn = false;
if (!$isUserLoggedIn) {
echo "Oops - you are not logged in!\n";
}
Oops - you are not logged in!
The example above is the same as ($isUserLoggedIn == false)
.
So we are basically checking whether false is false, which returns
true in this case.
I understand that this can be a little confusing. And to tell the truth,
even developers with many years or decades of coding experience
occasionally mess up here.
The else Statement
The else statement allows us to specify what should happen if the condition in the if statement is not met (returns false).
$isUserLoggedIn = false;
if ($isUserLoggedIn) {
echo "Yay - you are logged in!\n";
} else {
echo "You are not logged in!\n";
}
You are not logged in!
The elseif Statement
Sometimes two options are just not enough. For this purpose, we have
the elseif statement. It allows us to check if maybe a second
condition is met. The expression of the elseif part is only evaluated
when the if statement was not true.
By the way - you can have multiple elseif blocks.
$userType = 'moderator';
if ($userType == 'admin') {
echo 'Wow - you are an admin!';
} elseif ($userType == 'moderator') {
echo 'You are a moderator - not bad!';
} elseif ($userType == 'user') {
echo 'You are a user - welcome buddy!';
} else {
echo 'What are you even?';
}
You are a moderator - not bad!
The switch-case Statement
The switch statement can be a little confusing in the beginning. Don't worry though - it is rarely used in comparison to the others.
The main keywords here are switch
, case
, break
and optionally default
.
You can think of each case
as an if statement and the optional default
is like an else, which is executed/triggered when none of the cases above matched.
The break
keyword basically tells PHP to stop evaluating further.
$userType = 'moderator';
switch ($userType) {
case 'admin':
echo 'Wow - you are an admin!';
break;
case 'moderator':
echo 'You are a moderator - not bad!';
break;
case 'user':
echo 'You are a user - welcome buddy!';
break;
default:
echo 'What are you even?';
}
You are a moderator - not bad!
The Ternary Operator ?:
This weird looking operator is also known as the Elvis operator or the shorthand if-else statement. There are two ways to use it.
$today = 'Monday';
// consider this regular if & else statement
if ($today == 'Sunday') {
$message = 'closed';
} else {
$message = 'open for business';
}
// and now the ternary operator in comparison
$message = $today == 'Sunday'
? 'closed'
: 'open for business';
echo $message;
open for business
The second way to use the ternary operator is a little more tricky.
In PHP - apart from false itself - there are several other values
which are considered false
by nature.
- the int value
0
- the string value
'0'
- the float value
0.0
- and empty string
''
- the value
null
- an empty array with no values
[]
By using the ternary operator, we basically tell PHP to use the value on the left, if it's not considered a false value otherwise, use the value on the right.
var_dump('value' ?: 'default');
var_dump('' ?: 'default');
var_dump(0 ?: 'default');
var_dump(null ?: 'default');
string(5) "value"
string(7) "default"
string(7) "default"
string(7) "default"
The Null Coalescing Operator ??
And yet another weird operator. This one checks whether a variable exists
and actually has a value. Remember how the type null
is a way of saying that
something exists but has no value?
What this operator does could be described as: if the value to the left exists and is not null, use it. Otherwise, use the value on the right.
var_dump('value' ?? 'default');
var_dump('' ?? 'default');
var_dump(0 ?? 'default');
var_dump(null ?? 'default');
string(5) "value"
string(0) ""
int(0)
string(7) "default"
Logical Operators
To add to the confusion, there are so-called logical operators.
The two most commonly used ones within control structures are
the logical and &&
and the logical or ||
.
By using the &&
operator, we enforce that two or more expressions
must return true in order fulfill the requirements.
$accountBalance = 100;
$accountStatus = 'locked';
if ($accountBalance > 0 && $accountStatus != 'locked') {
echo "Success: You got $$ and your account is not locked\n";
} else {
echo "Error: You either got no $$ or your account is locked\n";
}
Error: You either got no $$ or your account is locked
Even though the account balance is positive, the account is locked, hence the error message is displayed. Only by changing the value of $accountStatus to something different, will the success message be displayed.
The ||
operator, on the other hand, allows us to tell PHP that at
least one of the expressions must return true. As soon as one condition
returns true, all others on the right hand side are skipped.
$accountBalance = -123;
$accountType = 'credit';
if ($accountBalance > 0 || $accountType == 'credit') {
echo "Success: You either got $$ or your account type is credit\n";
}
Success: You either got $$ or your account type is credit
Even though the account balance is negative, we get the success message because the account type is credit.
Alright, that was a lot of info to digest and it will definitely take some time and practice to get used to all these. The best way is to play around and try all kinds of combinations for yourself.
previous : : Data Types In Phpnext : : For Foreach And While Loops In Php