PHP: Math, comparisons, and conditions

Arithmetic operations comparison of values are fundamental things that you need to do in any language.  PHP is not any different.  Let’s cover how it handles them.

Let’s start with the arithmetic operators …

Operation Operator
Addition +
Subtraction
Multiplication *
Division /
Modulus %
Increment by 1 ++
Decrement by 1

 

For the increment and decrement operators, keep in mine that it does matter if the operator is before or after the variable.

Now that we can do math, let’s look at booleans and comparisons.  In PHP, false can be represented as: false, null, 0, 0.0, ‘0’, ”, “”, an empty array, or SimpleXML object created from empty tags.  Everything else is true.  This means that the string “false” is actually true since it isn’t in the list of PHP’s falsey values.

So, what does a conditional statement look like, within PHP?

<?php
    if (False){
        // Thing 1
    } elseif (True){
        // Thing 2
    } else {
        // Thing 3
    }
?>

It is a fairly similar syntax to other languages.  So, how do you compare non-boolean values, in PHP?

 

Symbol Meaning
 ==  Equal
 !=  Not Equal
 ===  Identical (compares datatype)
 !==  Not identical (compares datatype)
 >  Greater than
 >=  Greater than or equal to
 <  Less than
 <=  Less than or equal to

 

You should pay special attention to the identical / not identical operators, above.  Now, let’s say that you have more than one comparison that you would like to do at a time.  If you want to test more than one comparison, you can use ‘&&‘ or ‘||‘.  You can also test not something, using ‘!’.

So, let’s say that you want to write this condition

<?php
    $name = 'Joe';

    if($name == 'Joe'){
        $coolness = 'extreme';
    } else {
        $coolness = 'not as much';
    }

    echo $coolness;
?>

PHP does have a shortcut, in the Ternary Operator.  The above code can be written as

<?php
    $name = 'Joe';

    $coolness = ($name == 'Joe') ? 'extreme' : 'not as much';

    echo $coolness;
?>

In addition to “if, elseif, else” statements, you can do switch statements in PHP.  You can write a switch like this

<?php
    $name = 'Joe';

    switch($name){
        case 'Joe':
            echo 'He's cool.';
            break;
        case 'Tom':
            echo 'He's ok.';
            break;
        default:
            echo 'Who's that?';
    }
?>

So, what does ‘break’ do?  It prevents execution from going any further.  If it wasn’t in there, it would load every single case after the one that was triggered.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *