Now that the basics have been covered in the previous two posts, I’ll continue with some thing a bit more useful… writing some logic.
Conditional Statements
In PHP the conditional operators are pretty much the same as in C#, however there are some subtle differences.
==
and !=
use type coercion. That means that if the type on the left side is not the same as the type on the right side then PHP will coerce them so that they can be compared. For example:
$a = 1; $b = 1.0; if ($a == $b) echo 'a and b are equal.'; else echo 'a and b are not equal.';
It even works if one of them is a string representation of the number one.
To get the functionality you’d expect in C# you need to use ===
and !==
.
There is also an additional not equals operator similar to ==
that consists of a left and right cheveron: <>
Be careful of accidentally using a single equal sign for comparison. In C# the compiler will issue an error if it doesn’t evaluate to a Boolean. However, in PHP everything can be evaluated as a Boolean (see the section on Booleans in my previous post).
You can join comparisons together with &&
or ||
just like in C#, however, PHP also supports the use of and
or or
.
if
statements also support an elseif
clause in PHP.
if ($a < 123) { // Do stuff } elseif ($a == 123) { // Do other stuff } else { // Do different stuff }
Unlike C#, switch
statements allow one case
clause to drop in to the next, so it does not require a break
at the end of each case
block. The break
on the last case
or default
is not necessary either.
switch($a) { case 1: // Do some stuff break; case 2: // Do stuff case 3: // Do stuff (and continue case 2 if necessary) break; default: // Do stuff for all other cases break; }
Loops
PHP, like C#, has a number of loop statements depending on what you want to do.
for
loops, while
, and do
… while
work exactly the same way. So I won’t discuss them further.
Just like C#, you can break
out of a loop, and continue
to the next iteration of the loop.