PHP Operators
Operators and Operands
Up to this point we have been working with only a handful of operators such as the assignment operator and some basic arithmetic operators. PHP offers many other kinds of operators, we’ll cover and explain them in this tutorial.
An operator is a symbol that is used to perform a particular action on a operand, which is the input data used in the operation. For example, in the following expression: 2 + 3, the (+) symbol represents an operator and the numerical values 2 and 3 represent operands. PHP supports three types of operators, unary, binary, and ternary which operate on single operands, two operands, and three operands, respectively.
To hit the ground running, below is a table containing a complete listing of all operators available in PHP, with the highest-precedence operators at the top along with their associativity.
| Operators | Associativity |
|---|---|
| () | N/A |
| new | N/A |
| [] | Right |
| ! ~ ++ — (int) (double) (string) (array) (object) @ | Right |
| / * % | Left |
| + – . | Left |
| << >> | left |
| < <= > >= | N/A |
| == != === !== | N/A |
| & | Left |
| ^ | Left |
| | | Left |
| && | Left |
| || | Left |
| ? : | Left |
| = += -= *= /= .= %= &= |= ^= ~= <<= >>= | Left |
| Right | |
| AND | Left |
| XOR | Left |
| OR | Left |
| , | Left |
Precedence and Associativity
In complicated expressions involving two or more operators, PHP follows an internal set of precedence rules that govern the order in which the operators are evaluated. PHP also follows a standard set of associativity rules that specify the direction in which operators of the same precedence are processed in an expression, it can be either left to right, right to left, or not associative. We’ll follow with a couple of examples to help clarify these rules.
<?php /* Precedence Example */ $num = 5 + 2 * 10; /* Associativity Example */ $a = 2 / 2 * 5; ?>
In the precedence example, the value stored in $num is 25 instead in 70, because the multiplication operator (*) has a higher precedence then the addition operator (+), thus the PHP interpreter evaluates 2 * 10 first and then adds that to 5, resulting in 25. Since both the division operator (/) and multiplication operator (*) have the same precedence in the second example, PHP evaluates the expression based on the operators’ associative direction, in this case left to right, resulting in $a = 5.
You can use the parentheses () operator to explicitly force PHP to evaluate expressions based on your intent. Referring to the table above, you can see that the parentheses operator has the highest precedence, meaning PHP will evaluate expressions contained within them first.
Arithmetic Operators
Arithmetic operators perform basic math functions on expressions and are the most commonly used operators in PHP. Following is a table listing various PHP arithmetic operators.
| Operator | Name | Example |
|---|---|---|
| + | Addition | 2 + 2 = 4 |
| - | Subtraction | 2 – 2 = 0 |
| * | Multiplication | 2 * 4 = 8 |
| / | Division | 2 / 2 = 1 |
| % | Modulus | 25 % 10 = 5 |
At first glance, it might not be clear exactly what the modulus operators does. It returns the remainder that’s left over when preforming division on the operands in the expression. Consider the following example 25 % 10 = 5, this expression evaluates to the value 5, because this is the remainder calculated by dividing 25 by 10.
String Operators
PHP offers one string operator called the string concatenation operator (.). This operator is used to combine two or more strings together to form a single string.
| Operator | Name | Example |
|---|---|---|
| . | String Concatenation | $c = $a . $b |
Lets look at an example:
<?php $string1 = "cheese"; $string2 = "burger"; $new_string = $string1.$string2; echo $new_string; ?>
This is the output, if you run the above script:
cheeseburger
Assignment Operators
Following is a table that lists the assignment operators used in PHP, along with corresponding examples showing their use.
| Operator | Name | Example | Same As |
|---|---|---|---|
| = | Assignment | $var = 10 | $var = 10 |
| += | Addition Assignment | $var += 10 | $var = $var + 10 |
| -= | Subtraction Assignment | $var -= 2 | $var = $var – 2 |
| *= | Multiplication Assignment | $var *= 5 | $var = $var * 5 |
| /= | Division Assignment | $var /= 5 | $var = $var / 5 |
| .= | Concatenation Assignment | $var .= 5 | $var = $var . 5 |
You should already be familiar with the assignment operator (=), as we’ve used this operator before in various examples, we’ll mention it here to help jog your memory. This operator is called a simple assignment operator and contrary to conventional math, it’s not used in the same context as representing equality, but rather it is used to store or “assign” a data value to a variable. PHP provides a separate operator (==) for testing equality, which we’ll look at later.
The remaining operators in the table are referred to as combined or shortcut operators as they enable us to perform an additional operation on a variable before assigning the result to that variable. Combination operators don’t provide any new functionality, they essentailly provide a minimalist mechanism for performing two operations with one operator.
Increment and Decrement Operators
| Operator | Name | Example |
|---|---|---|
| ++ | Increment | ++$a or $a++ |
| – | Decrement | –$a or $a– |
Increment (++) and decrement (–) operators provide a shorthand way of adding or subtracting the value stored in a variable by 1, and then assigning that value back to the variable. The increment (++) or decrement (–) operators can be placed before a variable, known as pre-increment/decrement operators or they can be placed after a variable, which in this case would be referred to as post- increment/decrement operators. Depending on the placement of the operators relative to the variable, each will have a different effect on the outcome.
Lets look at an example:
<?php $num = 5; print "num is : " . ++$num . "<br>"; //Pre-increment $var = 5; print "var is : " . $var++ . "<br>"; //Post-increment print ($var); ?>
The output of the above code:
num is : 6
var is : 5
6
In the above example, we used the pre-increment operator with the $num variable, which causes the value of $num to be first incremented by 1 and then assigned back to $num changing its value from 5 to 6 before being displayed. Now, since we are using the post-increment operator in the second example, the outcome is slightly different. In the print statement, the current value of $var, which is 5 is displayed first and then incremented by 1, which is essentially the opposite effect of the pre-increment operator. After, the print "var is : " . $var++ . "<br>"; statement has executed, the valve of $var has been changed to 6, which is apparent in the last print statement.
The pre- and post-decrement operators work in the same manner, except the values are decremented instead of incremented.
Relational Operators
A relational operator tests for a relationship between two operands. They compare operands according to a relationship to see if that relationship exists between the operands, and if it does exist the result of the expression is a Boolean 1 (TRUE), otherwise its 0 (FALSE). What kind of relationships can the operators test for? Relational operators can test for equality or inequality between two values, they can test for comparative relationships such as “greater than” or “less than”, and test for logical relationships.
The remaining operators that we’ll cover in this tutorial are all examples of relational operators, which return either TRUE or FALSE depending on the condition.
Equality Operators
| Operator | Name | Example | Returns True If.. |
|---|---|---|---|
| == | Equals | $a == $b | $a is equal to $b |
| === | Identical | $a === $b | both $a and $b are equivalent and of the same datatype |
| != | Not Equal | $a != $b | $a is not equal to $b |
| !== | Not Identical | $a !== $b | $a and $b are not of the same datatype |
Equality operators do exactly what their name implies, they are used to test for equality between two operands and return a Boolean TRUE or FALSE depending on the values. The identical operators will only return TRUE if both operands are equivalent and of the same data-type.
Consider the following examples:
5 == 5 //true 5 != 6 //true 2 === '2' //false
Note the last example returns FALSE because even though the values are the same, we are comparing two different date types; one is an integer and the other is a string.
It is very common for both new programmers and experienced programmers alike to use the assignment operator (=) instead of the equals operator (==) to test for equality. If you intend to test for equality between two variables by using only one equal sign, as in $a = $b, PHP will interpret this as an assignment statement and assign the value stored in $b to $a. Note, if you make this mistake PHP will not give an error, since the syntax is correct, but logically it would produce the wrong results.
Comparison Operators
Comparison operators are used to compare two values and as you might have already guessed, they return either a true or false depending on the comparison.
| Operator | Name | Example | Returns True If.. |
|---|---|---|---|
| < | Less than | $a < $b | $a is less than $b |
| > | Greater than | $a > $b | $a is greater than $b |
| <= | Less than or equal to | $a <= $b | $a is less than or equal to $b |
| >= | Greater than or equal to | $a >= $b | $a is greater than or equal to $b |
Some examples of comparison operators:
5 < 10 //true 5 > 2 //true 5 >= 5 //true 5 <= 4 //true
Logical Operators
Throughout your PHP scripts, you'll frequently need to test more than two conditions. Logical operators allow you to test a series of conditions and return TRUE or FALSE depending on if all or some of the conditions are true. The following is a table summarizing PHP logical operators:
| Operator | Name | Example | Returns True If.. |
|---|---|---|---|
| && | And | $a && $b | both $a and $b are true |
| AND | And | $a AND $b | both $a and $b are true |
| || | Or | $a || $b | either $a or $b is true |
| OR | Or | $a OR $b | either $a or $b is true |
| ! | Not | !$a | $a is not true |
| NOT | Not | NOT $a | $a is not true |
| XOR | Exclusive Or | $a XOR $b | only $a or only $b is true |
Lets look at some examples:
5 > 2 && 5 < 10 //true 10 < 20 || 10 < 5 //true
The logical AND operator (&&) will return TRUE only if all operands evaluate to TRUE. In the first example the entire expression returns true, since the expression on the left (5 > 2) returns a boolean value of true same as the expression on the right (5 < 10). The OR operator (||) returns true if any of the conditions evaluate to true, otherwise it returns false. This is apparent in the second example, note the expression on the left is true (10 < 20), but the expression on the right is false (10 < 5), since we are using the logical OR operator; either condition returning true will cause the entire expression to return true.
Relational operators will prove invaluable, when we combine them with control structures, such as "if" statements and loops, and how this combination will open a whole new door of functionality for creating intelligent and interactive scripts. In the next tutorial, we'll start our discussion on conditional statements which allow us to make decisions within our scripts.
