php.w3clubs.com

PHP tutorials and articles

 

If-else conditions

Here's an important construct in any programming language - the ability to branch program execution based on a result of a condition (a check).

What if?

Think about this expression - If I reach the train station before 8:30 I'll catch the train, otherwise I'll have to wait for the next one. In some sort of programspeak pseudo-language this will look like:

if time less than 8:30
  catch the train
else
  wait the next one
endif

The "time less than 8:30" part is called a condition. A condition returns a boolean value - either TRUE or FALSE. If it returns TRUE, the next statement "catch the train" is executed. If the condition returns (evaluates to) FALSE, the else part ("wait for the next one") is executed.

A PHP example

Let's see an example with real PHP code.

$a = 5;
if ($a > 1) {
    echo 'a is positive';
} else {
    echo 'a is negative or 0';
}

The syntax is that the condition is placed in brackets and the statements are in curly brackets.

Comparison operators

We already discussed some operators, but not all. Let's introduce some more, the so-called conditional operators.

  • $a == $b returns TRUE if $a and $b are equal
  • $a === $b returns TRUE if $a and $b are equal and are of the same type. For example if we have $a = 1 (integer) and $b = "1" (string), then $a == $b will return TRUE, but $a === $b will return FALSE
  • $a != $b returns TRUE if $a and $b are NOT equal
  • $a !== $b returns TRUE if $a and $b are NOT equal or not of the same type. Again if we have $a = 1 (integer) and $b = "1" (string), then $a != $b will return FALSE, but $a !== $b will return TRUE. Yes, think about it for a minute.
  • $a > $b returns TRUE if $a is greater than $b
  • $a < $b returns TRUE if $a is less than $b
  • $a >= $b returns TRUE if $a is greater than or equal to $b
  • $a <= $b returns TRUE if $a is less than or equal to $b
  • $a $b returns TRUE if $a is either greater or less than $b, or in other words $a and $b are NOT equal (same as !=, rarely seen in practice)

The == operator is easily confused with the simple assignment =. When you use assignment in an if-condition, it's not an error, and in most cases you'll get the condition evaluated to TRUE, simply because the assignment was successful. For example:

$a = 5;
if ($a = 1) {
    echo $a;
} else {
    echo "A is not 1";
}

This code will print "1", because in the condition part instead of using == to check if $a is 1, we used assignment and gave $a the value 1. If we use comparison operator, the result will be "A is not 1".

$a = 5;
if ($a == 1) {
    echo $a;
} else {
    echo "A is not 1";
}

The block

The code enclosed in curly brackets { and } is called a block. It's an important concept in PHP (also in C, Java). We'll see more use of the blocks further on, for example in functions and loops.

One note on syntax - when you have an if codition and a block is only one line, the brackets are optional. So this is valid:

$a = 123;

// checking a
if ($a == 3)
  echo 'A is three';

// moving on
$a = 321;

A good practice is to use the brackets, even if they are not needed. This makes it easier to understand the code, no need to think about it. Also makes a bit easier to come to the code later and add a second line of code, in this case the brackets are required and they would already be there.

Conditions

Sometimes a simple check like $a == $b is all you need, but other times you'll need a more specific set of checks. It's OK to have as many checks as you want in a single condition.

if ($a > 10 && $a < 100) {
    echo "A is between 10 and 100";
}

&& means AND. Its opposite is || which means OR. So the condition above can be read as "if a is greater than 10 and less than 100".

Here's another example, it can be read "if a is equal to 10 or to 100"

if ($a == 10 || $a == 100) {
    echo "A is either 10 or 100";
}

If you use || and at least one of the sub-conditions is TRUE, then the whole thing is TRUE. With && it's the other way around - all individual sub-conditions have to be TRUE, otherwise the whole condition is FALSE. This has a performance impact, because PHP is smart enough to give up if at some point during the evaluation of the separate sub-conditions, the end result becomes clear. For example:

$a = 1;
if ($a == 5 && $a > 10 && $a < 1) {
    // some code
}

In this case after the first check $a == 5 evaluates to FALSE, it becomes clear that the whole condition has no chance of being TRUE, so PHP will not execute all the following checks.

The performance lesson here is - put the most likely sub-conditions first, this might save some processing.

You can also mix && and || in the same condition. If you find yourself writing a longer condition consisting of sub-conditions, use brackets to make the code easier to follow.

// hard to understand
if ($a == 5 && $b == 5 || $a == 10 && $b == 10) {}
// much better
if (($a == 5 && $b == 5) || ($a == 10 && $b == 10)) {}

else and elseif

As you see in some of the examples above, the else clause is not required, it's optional.

There is also elseif which you can use for a better execution control.

if ($a == 1) {
  echo 'A is 1';
} elseif ($a == 2) {
  echo 'A is 2';
} else if ($a == 3) {
  echo 'A is 3';
} else {
  echo 'I give up';
}

Both elseif and else if are OK.

Truthy and falsy

You can use conditions like if ($a) {...}. The result of the condition will depend on the value in $a. Most of the values are "truthy" and the condition will evaluate to TRUE, except the following which are all "falsy":

  • "" (empty string). Note that a string with even a single space is truthy.
  • FALSE
  • NULL
  • 0

« to the PHP tutorial table of contents

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by WordPress, theme by ♣w3clubs.com, based on Kubrik and Sancta Simplicitas