|Previous||Table of Contents||Next|
|PHP Constants||PHP Flow Control and Looping|
Operators in PHP, and any other programming language for that matter, enable us to perform tasks on variables and values such as assign, multiply, add, subtract and concatenate them. Operators take the form of symbols (such as + and -) and combinations of symbols (such as ++ and +=).
Operators in PHP work with operands which specify the variables and values that are to be used in the particular operation. The number and location of these operands in relation to the operators (i.e. before and/or after the operator) depends on the type of operator in question. Let's take, for example, the following simple expression:
1 + 3;
In this expression we have one operator (the '+') and two operands (the numbers 1 and 3). The '+' operator adds the values of two operands (resulting in a value of 4).
Operators can be combined to create complete expressions:
$myVar = 1 + 3;
In the above example, the assignment operator (=) assigns the result of the addition to the operand represented by the variable $myVar. After evaluating this expression the value of 4 will have been assigned to the variable $myVar.
In this chapter of PHP Essentials we will explore each type of operator and explain how they are used in relation to their operands.
 PHP Assignment Operators
We briefly covered the basic PHP assignment operator in the An Introduction to PHP Variables chapter. We will now look at this and other assignment operators in more detail.
The assignment operator is used to assign a value to a variable and is represented by the equals (=) sign. The assignment operator can also be combined with arithmetic operators to combine an assignment with a mathematical operation (for example to multiply one value by another and assigning the result to the variable) and also to perform string concatenations.
The following table lists the seven assignment operators available in PHP, together with descriptions and examples of their use:
|=||Assignment||Sets the value of the left hand operand to the value of the right||$myVar = 30;|
|+=||Addition-Assignment||Adds the value of left hand operand to the value of the right hand operand and assigns result to left hand operand||$myVar = 10;
$myVar += 5;
|-=||Subtraction-Assignment||Subtracts the value of right hand operand from the value of the left hand operand and assigns result to left hand operand||$myVar = 10;
$myVar -= 5;
|*=||Multiplication-Assignment||Multiplies the left hand operand by value of the right hand operand assigning result to left hand operand||$myVar = 10;
$myVar *= 5;
|/=||Division-Assignment||Divides the left hand operand by value of the right hand operand assigning result to left hand operand||$myVar = 10;
$myVar /= 5;
|%=||Modulo-Assignment||Sets the value of the left hand operand to the remainder of the value after being divided by the right hand operand||$myVar = 10;
$myVar %= 5;
|.=||Concatenation-Operand||Sets the value of the left hand operand to a string containing a concatenation of its value appended with the string in the right hand operand||$sampleString="My color is ";|
$sampleString .= "blue";
 PHP Arithmetic Operators
As the name suggests PHP arithmetic operators provide a mechanism for performing mathematical operations:
|+||Addition||Calculates the sum of two operands||$total = 10 + 20;|
|-||Subtraction||Calculates the difference between two operands||$total = 10 - 20;|
|*||Multiplication||Multiplies two operands||$total = 10 * 20;|
|/||Division||Divides two operands||$total = 10 / 20;|
|%||Modulus||Returns the remainder from dividing the first operand by the second||$total = 20%10;|
Arithmetic operators work with two operands, one to the left and the other to the right of the operator. For example:
$var = 1 + 2; // Sets variable $var to the sum of 1 + 2 $var = 3 % 7; // Sets variable $var to the modulus of 3 and 7 $var = 10; $var2 = $var / 2; // Sets variable $var2 to the value of 10 divided by 2
 PHP Comparison Operators
The comparison operators provide the ability to compare one value against another and return either a true or false result depending on the status of the match. For example, you might use a comparison operator to check if a variable value matches a particular number, or whether one string is identical to another. PHP provides a wide selection of comparison operators for just about every comparison need.
The comparison operators are used with two operands, one to the left and one to the right of the operator. The following table outlines the PHP comparison operators and provides brief descriptions and examples:
|==||Equal to||Returns true if first operand equals second||$myVar = 10;
if ($myVar == 10)
echo 'myVar equals 10';
|!=||Not equal to||Returns true if first operand is not equal to second||$myVar = 10;
if ($myVar != 20)
echo 'myVar does not equal 10';
|<>||Not equal to||Returns true if first operand is not equal to second||$myVar = 10;
if ($myVar <> 20)
echo 'myVar does not equal 10';
|===||Identical to||Returns true if first operand equals second in both value and type||$myVar = 10;
if ($myVar === $myString)
echo 'myVar and myString are same type and value';
|!==||Not identical to||Returns true if first operand is not identical to second in both value and type||$myVar = 10;
if ($myVar !== $myString)
echo 'myVar and myString are not same type and value';
|<||Less than||Returns true if the value of the first operand is less than the second||$myVar = 10;
if ($myVar < 20)
echo 'myVar if less than 20';
|>||Greater than||Returns true if the value of the first operand is greater than the second||$myVar = 10;
if ($myVar > 5)
echo 'myVar if greater than 5';
|<=||Less than or equal to||Returns true if the value of the first operand is less than, or equal to, the second||$myVar = 10;
if ($myVar <= 5)
echo 'myVar is less than or equal to 5';
|>=||Greater than or equal to||Returns true if the value of the first operand is greater than, or equal to, the second||$myVar = 10;
if ($myVar >= 5)
echo 'myVar is greater than or equal to 5';
 PHP Logical Operators
Logical Operators are also known as Boolean Operators because they evaluate parts of an expression and return a true or false value, allowing decisions to be made about how a script should proceed. The logical operators supported by PHP are listed in the following table:
|&&||AND||Performs a logical "AND" operation.||if (($var1 < 25) && ($var2 > 45))|
|||||OR||Performs a logical "OR" operation.||if (($var1 < 25) || ($var2 > 45))|
|xor||XOR||Performs a logical "XOR" (exclusive OR) operation.||if (($var1 < 25) xor ($var1 > 45))|
The first step to understanding how logical operators work is to construct a sentence rather than to look at a script example right away. Let's assume we need to check some aspect of two variables named $var1 and $var2. Our sentence might read:
If $var1 is less than 25 AND $var2 is greater than 45 display a message.
Here the logical operator is the "AND" part of the sentence. If we were to express this in PHP we would use the comparison operators we covered earlier together with the && logical operator:
if (($var1 < 25) && ($var2 > 45)) echo 'Our expression is true';
Similarly, if our sentence was to read:
If $var1 is less than 25 OR $var2 is greater than 45 display a message.
Then we would replace the "OR" with the PHP equivalent ||:
if (($var1 < 25) || ($var2 > 45)) echo 'Our expression is true';
Another useful logical operator is the Exclusive Or (XOR) operator. The XOR operator returns true if only one of the expressions evaluates to be true. For example:
If $var is EITHER less than 25 OR greater than 45 display a message
We represent XOR with the keyword xor:
if (($var1 < 25) xor ($var1 > 45)) echo 'Our expression is true';
The final Logical Operator is the NOT operator which simply inverts the result of an expression. The ! character represents the NOT operator and can be used as follows:
(10 > 1) // returns ''true'' !(10 > 1) // returns ''false'' because we have inverted the result with the logical NOT
 PHP Increment and Decrement Operators
When programming in any language it is not uncommon to need to increment or decrement the value stored in a variable by 1. This could be done long hand:
$myVar = $myVar-1;
A much quicker way, however, is to use the PHP increment and decrement operators. These consist of the operators ++ (to increment) and -- (to decrement) combined with an operand (the name of the variable to which the change is to be applied).
There are two ways of using these operators, pre and post. The pre mode performs the increment or decrement before performing the rest of the expression. For example, you might want to increment the value of a variable before it is assigned to another variable, or used in a calculation. In the post mode the increment or decrement is performed after the expression has been performed. In this instance, you might want the value to be decremented after it has been assigned or used in a calculation.
Whether a pre or post is used depends on whether the operator appears before (for pre), or after (for post) the variable name in the expression. For example --$myVariable or $myVariable++.
The following table outlines the various forms of pre and post increment and decrement operators, together with examples that show how the equivalent task would need to be performed without the increment and decrement operators.
|++$var||Preincrement||Increments the variable value before it is used in rest of expression||$var = 10;
$var2 = $var + 1;
|--$var||Predecrement||Decrements the variable value before it is used in rest of expression||$var = 10;
$var2 = $var - 1;
|$var++||Postincrement||Increments the variable value after it is used in rest of expression||$var = 10;
$var2 = $var;
$var = $var + 1;
|$var--||Postdecrement||Decrements the variable value after it is used in rest of expression||$var = 10;
$var2 = $var;
$var = $var - 1;
 PHP String Concatenation Operator
The PHP String concatenation operator is used to combine values to create a string. The concatenation operator is represented by a period/full stop (.) and can be used to build a string from other strings, variables containing non-strings (such as numbers) and even constants:
We will start with the operator in its simplest form concatenating two strings:
echo 'My favorite color is ' . 'blue.';
The above example will display a string that is the result of second string appended to the end of the first string:
My favorite color is blue.
The string concatenation operator can also be used with variables. In the following example the value of the $myString variable is appended to the end of the string:
$myString = "red"; echo 'My favorite color is ' . $myString;
We can also reference constants (see PHP Constants for details on using constants in PHP) when using concatenation:
define (MY_COLOR, "Green"); echo 'My favorite color is ' . MY_COLOR;
The above example will result in the following output:
My favorite color is Green
 Concatenation of Numbers and Strings in PHP
We mentioned at the beginning of this section that it is also possible to mix numbers and strings in a concatenation operation to create strings. For example we can include the number 6 in our string as follows:
echo 6 . ' is my lucky number';
The above example will create output as follows:
6 is my lucky number
We can also perform a calculation and have the result included in the concatenation:
echo 6 + 5 . ' is my lucky number'
In this example the mathematical operation will be evaluated before the concatenation, thereby producing:
11 is my lucky number
It is important to note an issue when dealing with strings and numbers. While the above works fine because we began the expression with the addition, something very different happens when we have the addition after the string:
echo 'My Lucky number is ' . 6 + 5;
The above will produce unexpected results (typically it will output just the number 5). The reason for this is because we have asked PHP to take a string (My Lucky number is ), append the number 6 to it (to produce My Lucky number is 6) and then finally arithmetically add the number 5 to the string (which doesn't make a lot of sense). To resolve this issue we need to tell the PHP pre-processor to perform the addition (6 + 5) before performing the concatenation. We can achieve this by surrounding the addition expression in parentheses. Therefore the modified script:
echo 'My Lucky number is ' . (6 + 5);
This will now produce the desired output:
My Lucky number is 11
Through the use of parentheses around the addition expression we have changed the operator precedence for that expression.
 PHP Execution Operator - Executing Server Side Commands
All of the operators we have looked at so far are similar to those available in other programming and scripting languages. With the execution operator, however, we begin to experience the power of PHP as server side scripting environment. The execution operator allows us to execute a command on the operating system that hosts your web server and PHP module and then capture the output.
You can do anything in an execution operator that you could do as if you were sitting at a terminal window on the computer (within the confines of the user account under which PHP is running). Given this fact, it should not escape your attention that there are potential security risks to this, so this PHP feature should be used with care.
The execution operator consists of enclosing the command to be executed in back quotes (`). The following example runs the UNIX/Linux uname and id commands to display information about the operating system and user account on which the web server and PHP module are running (note that these command will not work if you are running a Windows based server):
<?php echo `uname -a` . '<br>'; echo `id`; ?>
This results in the following output in the browser window:
Linux techotopia 2.6.9-42.0.10.ELsmp #1 SMP Tue Feb 27 10:11:19 EST 2007 i686 i686 i386 GNU/Linux
uid=48(apache) gid=48(apache) groups=48(apache)
On a Windows system you could run the dir command to get a listing of files in the current web server directory:
<?php echo `dir`; ?>
|Purchase and download the full PDF and ePub versions of this PHP eBook for only $8.99|