PHP Basics Series – Conditional Statements

PHP Conditionals Statements are a true variation from C/C++ and they are, in fact, decision making structures. They are part of a set of control structures that is in fact your toolbox of PHP code.

For truly understanding how a conditional statement work, you have to get back to real hardware logical structures. When you study digital designs you learn that every processor, multiplex, works with a bunch of elements that, according is set on the circuit board, decisions will be made getting the correct result for you (click in the image).

When working with PHP conditional statements you will find most of those real elements that you find inside many electric hardware and they are as important as such. Just keep in mind, whenever you need to code a decision, you will need at least 1 conditional statement.

PHP’s conditional statements are:

[Note:] all PHP structures are lower case

Most likely, when working with a if statement, you will be also working with a else statement, but, in some cases, where you have a nested or sequenced structure with many if and else’s, your best choice will be the switch.

The if and else statement are pretty simple:

<?php
if ( expression )
{
// do what needs to be done
}
?>

If you got another situation that you also need to test, but is just one more situation, then you will use the else, following the if.

<?php
if ( expression )
{
// do what you need to do
}
else
{
// was not what you expected before, so do this now
}
?>

To better visualize the code, let’s take a real situation, for instance, parsing the information sent by posting a form.

<?php
$name = ”;
if ($_POST[‘login’] == ‘John’)
{
$name = $_POST[‘login’];
}
else
{
echo ‘Error: Unable to log into the system. Wrong username.’;
}
?>

Some times will be needed to handle more than one else statement, or more than one condition to test after the first condition (if). There are actually 2 ways to do that, sequence some else followed by a if, or better known as elseif, or use the switch. There is no real rule to when to use what, but here is a tip, if you have more than 1 elseif, then use a switch.

<?php
if (expression)
{
// do what you got do
}
else if (another condition)
{
// do another thing
}
else
{
// last condition
}
?>

The code can be written, also,  using a elseif, instead of a else if. No real difference between the both, so it will be more how the programmer likes to code. Anyway, as mentioned before, when you have a long sequence of elseif’s, in most of the cases, you will be able to replace them for a switch structure.

The switch statement will allow to compare a same variable with a bunch of different values and you can easily math one or more comparisons to the same action.

<?php
switch ($_POST[‘todaysDuties’])
{
case ‘take garbage out’: // consider the case as a if
$need = true;
break; // and always add a break, otherwise it will continue to the next statement

case ‘take dog to the vet’:
case ‘give dog a bath’: // here we are seeing 2 conditions set to the same action
$need = false;
break;

default: // this is the default statement, or better know as else
// do nothing
break;
}
?>

[Note:] If you need to do a comparison that have more than one condition such as if equals something, or bigger than something else, place the condition inside parenthesis. Just like a if statement, it will look if the condition is true or false, so the conditions need to be worked as math expressions so the result is always correct, or the expected result.

Looking at the figure (top of the article), it shows a logical diagram for a circuit in which will get the signal entries from x1 to xn, invert them (or saying NO to it), pass them into a AND array, going to a OR array and finally going to an XOR array that will result the final output. These elements, that will return some logical choices of true or false when combined, are also used on combined expressions of an conditional statement.

The most common operators that is used inside a conditional statement are:

  • == : double equals : equals to (a single equal is receiving some value)
  • === : triple equals : identical to (in every single way, from type to value)
  • || : double bars : or
  • && : double commercial e’s : and
  • ! : exclamation point : not
  • != : exclamation point followed by a equal : not equal to
  • >, <, >=, <= : numerical operators

For example porpoises only a if statement could be easily represented by:

<?php
if ( ((!expression) && (expression)) || (expression))
{
// do something
}
else
{
// do something else
}
?>

There is another way to declare if / else statements in a single line without using the if or else. This is the short version of the code and, even knowing that it’s easier to use it while declaring variables or echoing, keep in mind that many developers does not know or can easily read them.

A short version of an if / else is declared as:

<?php
$variable = (expression) ? ‘get this value’ : ‘get another value’;
// this can be read as the variable will receive ‘get this value’ if the expression is true, else, it will ‘get another value’
?>

The same can be done to be used while outputting something and it also can support in-line (nested) short statements (not recommended – harder to read).

As many others controllers and structures from PHP, the conditional statements can be nested in many levels and can also be included inside other control structures.

To better practice how the conditional statements work, look for questions that can be programmable and the result of the conditional expression can be set to true,  false or maybe (in this case, an elseif that will return true or false).

Have fun.

Advertisements

About mcloide

Making things simpler, just check: http://www.mcloide.com View all posts by mcloide

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: