PHP Tutorials

Tutorial 4 - Operators

So far, we have mainly looked at ways that we can handle and manipulate strings. However PHP has a variety of other uses - one of which being "operators". As PHP.net concisely defines them, "an operator is something that you feed with one or more values which yields another value". For example, an operator can take the form of addition (e.g. 2 + 8, which will output 10) or a compaison (e.g. 5 > 3, which will return "true" or 'yes'). Operators are useful for a variety of reasons, and these are explored below.

There are four main types of operators:


Quick Reference:
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators

Arithmetic Operators Top

As mentioned above, arithmetic operators perform mathematical functions on the provided data. The following code examples show the various arithmetic operators, and how they work.


<?php

// The most basic arithmetic operator: addition
$x 3// This would set the value of $x to 5
$y 7// This would set the value of $y to 11

$z $x $y// This would add $x and $y together and assign its value to $z. In
              // other words: $z = 5 + 11 = 16

// Subtraction
$x 3// This would set the value of $x to 2
$y 10// This would set the value of $y to -8 (negative numbers are no
             // problem)

// Multiplication
$x 2// This would set the value of $x to 14

// Division
$x 10 5// This would set the value of $x to 2
$y 16 4// This would set the value of $y to 4

$z $x $y// This would divide $x by $y and set the value to $z. I.e.:
              // $z = 2 / 4 = 0.5

// Modulus (A slightly confusing one)
// Modulus does a division (as above), but then outputs the remainder of the
// division:
$x 2// This would set the value of $x to 1 - because 2 goes into 5 twice,
            // but then there is 1 left over
$y 12 5// This would set the value of $y to 2
$z 10 5// This would set the value of $z to 0

// Increment
// Sometimes it's necessary to, after performing a certain action, automatically
// increment a variable by 1 (an example here would be a counter - everytime an
// action is performed, the counter goes up by one):
$x 5;

$x++; // This would set the value of $x to 6. This is easier than doing
      // "$x = $x + 1;"

// Decrement
// To complement the above, it's also sometimes necessary to reduce a number by one
// every time an action is performed:
$x 10;

$x--; // This would set the value of $x to 9

?>

Assignment Operators Top

These are one of the easier operators to understand - they assign a given value to a variable:


<?php

// The most basic assignment operator.. (=)
$x 5// Simple enough - this is what we've been doing all along! The "="
        // operator simply assigns the value to the right of the "=" to the
        // variable on the left of the "="

// Addition assignment (+=)
$x 10;
$y 2;

$x += $y// This would set the value of $x to 12. The "+=" operator takes the form
          // of "$x += $y", and is the same as saying "$x = $x + $y"

// Subtraction assignment (-=)
$x 7;
$y 5;

$x -= $y// This would set the value of $x to 2. The "-=" operator takes the form
          // of "$x -= $y", and is the same as saying "$x = $x - $y"

// Multiplication assignment (*=)
$x 2;
$y 4;

$x *= $y// This would set the value of $x to 8 (i.e. 2 * 4 = 8).  The "*="
          // operator takes the form of "$x *= $y", and is the same as saying
          // "$x = $x * $y"

// Division assignment (/=)
$x 6;
$y 3;

$x /= $y// This would set the value of $x to 2 (i.e. 6 / 3 = 2).  The "/="
          // operator takes the form of "$x /= $y", and is the same as saying
          // "$x = $x / $y"

// Concatenation assignment (.=)
$x 'PHP ';
$y 'Mission';

$x .= $y// This would set the value of $x to "PHP Mission".  The ".=" operator
          // takes the form of "$x .= $y", and is the same as saying "$x = $x . $y"

// This concatenation assignment can be particularly useful for adding data to a
// variable as you go through the script (you don't have to have all the data
// available right away - instead you can add to the variable as you go through
// the script).

?>

Compaison Operators Top

Comparing data values (or a variable to a data value) can be very useful in deciding which actions to perform:


<?php

// The comparison operators are usually used in if statements (which are explored
// later in tutorial 5). However it obviously helps to put the below examples into
// some sort of context. Hence, for the following examples, just try and imagine
// that you would be saying IF [a given comparison/example] is TRUE, then DO THIS
// [some action]. This is basically how an IF statement works (i.e. by making a
// comparison, and then going from there).

// The "==" operator
$x 4;
$y 8/2// Also equal to 4

$x == $y// Compares whether the value of $x is equal to the value of $y - in this
          // case 4 == 4, hence this would return true.

$Weather 'Rain';

$Weather == 'Sun'// Checks to see whether the $Weather is "Sun" (however this
                   // would return as false, because $Weather is actually
                   // "Rain").

// The "!=" operator
$LikelyEuro2008Winner 'Spain';
$ActualEuro2008Winner 'Germany';

$LikelyEuro2008Winner != $ActualEuro2008Winner// Checks to see whether the
                                // $LikelyEuro2008Winner is different from the
                                // $ActualEuro2008Winner. In this case, "Spain"
                                // isn't equal to "Germany", hence it'd return
                                // true.

// The ">" (Greater than) operator
$x 5;
$y 3;

$x $y// This would return true because 5 > 3

$x 5;
$y 6;

$x $y// This would return false because 5 isn't greater than 6

$x 10;
$y 10;
$x $y// This would return false. Whilst $y (10) is clearly not less than $x
         // (10), it's not greater than it either. $x is actually equal to $y

// The ">=" (Greater than or equal to) operator
$x 5;
$y 5;

$x >= $y// This would return true because 5 >= 5 (i.e. 5 is greater than, or
          // EQUAL TO, 5)

$x 5;
$y 8;

$x >= $y// This would return false because 5 isn't greater than, or equal to, 8

// The "<" (Less than) operator
$x 4;
$y 6;

$x $y// This would return true because 4 < 6 (i.e. 4 is less than 6)

$x 7;
$y 4;

$x $y// This would return false because 7 isn't less than 4

// The "<=" (Less than or equal to) operator
$x 2;
$y 7;

$x <= $y// This would return true because 2 < 7 (i.e. 2 is less than 7)

$x 1;
$y 1;

$x <= $y// This would return true because 1 is less than, or EQUAL TO, 1

?>

Logical Operators Top

Logical operators are able to carry out a quick test to see whether something is something is true or false. These are very useful in if statements (as in tutorial 5).


<?php

// Logical operators are usually combined with comparison operators to check
// whether a certain test is true or not (for example, in plain English, to check
// whether the $Weather is "Rain" AND the $Day is "Tuesday" - i.e. sometimes it can
// be helpful to compare more than one test; here we checked the weather AND the
// day).

// The "&&" (AND) operator
$x 3;
$y 6;

$x == && $y 5// This would return true because $x is indeed equal to 3, and
                   // $y is indeed greater than 5

$Weather 'Rain';
$Day 'Thursday';

$Weather == 'Rain' && $Day != 'Monday'// This would also return true because
                                        // the $Weather is "Rain" and the $Day
                                        // is not equal to "Monday"

// The "||" (OR) operator
$Day 'Sunday';

$Day == 'Monday' || $Day == 'Wednesday'// This would return false because the
                                         // $Day is not equal to "Monday" OR
                                         // "Wednesday"

// Notice here that you can't simply do $Day == 'Monday' || 'Wednesday' - you
// must say $Day = 'SomeValue' || $Day = 'AnotherValue'

/* This does seem a bit weird, because for us it'd be logical to think:

If the $Day is equal to Monday or Wednesday

However, PHP is a bit quirky - hence we must actually specifically say:

If the $Day is equal to Monday, or if the $Day is equal to Wednesday

A bit weird, although this is PHP ;-) */

// The XOR operator
// Checks whether one expression OR the other is true, but both can't be true
$x 15;
$y 20;

$x 10 XOR $y >= 22// This would return true because $x is greater than 10,
                      // however $y isn't greater than or equal to 22. If both
                      // expressions were true (for example if $y = 24), this would
                      // return as false because XOR means if one OR THE OTHER is
                      // true (but not both)

// The "!" (NOT) operator
// This operator will check whether something is false (and so not true)
$x 3;
$y 6;

// At this point, it's clear than $x == $y would be false (because $x (3) is not
// equal to $y (6))
// However...

!($x == $y); // ... would actually return true because, by using "!", you are
             // looking for the opposite of the "==" operator

// In plain English, the above example would mean IF $x and $y are not (!) equal to
// each-other

?>

That should hopefully comprehensively cover the PHP operators! They can be a bit weird to get your head around at first (especially since we haven't covered IF statements yet), however they really are the building blocks of PHP.

In a typical PHP script, the first thing you'd do is to get all the relevant data together. After that, you'd usually use IF statements (and so the various operators) to decide what to do with the actual data.

This might seem hard to understand without seeing an actual example script - however think what would happen when you make a post on a message board:

As you can hopefully see from the above example, a large part of PHP is running tests (via IF statements and operators) on the data - this is mainly to check that it's valid. This is why this tutorial, and tutorial 5, are very important ones. Please ensure that you understand the various operators before continuing, because nothing's worse than having a script break due to a small flaw in the operator/test logic.