Operators and Expressions
With what you have learned so far, you can assign data to variables. You can even investigate and change the data type of a variable. A programming language isn't very useful, though, unless you can manipulate the data you have stored. Operators are symbols that make it possible to use one or more values to produce a new value. A value that is operated on by an operator is referred to as an operand.
4 + 5
4 and 5 are operands. They are operated on by the addition operator (+) to produce 9. Operators almost always sit between two operands, although you will see a few exceptions later in this chapter.The combination of operands with an operator to produce a result is called an expression . Although most operators form the basis of expressions, an expression need not contain an operator. In fact, an expression in PHP is defined as anything that can be used as a value. This includes integer constants such as 654, variables such as $user, and function calls such as gettype(). ( 4 + 5 ), for example, is an expression that consists of two further expressions and an operator. When an expression produces a value, it is often said to resolve to that value. That is, when all sub-expressions are taken into account, the expression can be treated as if it were a code for the value itself.
![]() | An expression is any combination of functions, values, and operators that resolve to a value. As a rule of thumb, if you can use it as if it were a value, it is an expression. |
The Assignment Operator
You have seen the assignment operator each time we have initialized a variable; it consists of the single character =. The assignment operator takes the value of its right-hand operand and assigns it to its left-hand operand:
$name = "matt";
The variable $name now contains the string "matt". Interestingly, this construct is an expression. It might appear at first glance that the assignment operator simply changes the variable $name without producing a value, but in fact, a statement that uses the assignment operator always resolves to a copy of the value of the right operand. Thus
echo $name = "matt";
prints the string "matt" to the browser in addition to assigning the value "matt" to the $name variable.
Arithmetic Operators
The arithmetic operators do exactly what you would expectthey perform arithmetic operations. Table 4.3 lists these operators. The addition operator adds the right operand to the left operand. The subtraction operator subtracts the right-hand operand from the left. The division operator divides the left-hand operand by the right. The multiplication operator multiplies the left-hand operand by the right. The modulus operator returns the remainder of the left operand divided by the right.
Operator | Name | Example | Example Result |
---|---|---|---|
+ | Addition | 10+3 | 13 |
- | Subtraction | 10-3 | 7 |
/ | Division | 10/3 | 3.3333333333333 |
* | Multiplication | 10*3 | 30 |
% | Modulus | 10%3 | 1 |
The Concatenation Operator
The concatenation operator is represented by a single period (.). Treating both operands as strings, this operator appends the right-hand operand to the left. So
"hello"." world"
returns
"hello world"
Note that the resulting space between the words occurs because there is a leading space in the second operand. The concatenation operator literally smashes together two strings, without adding any of its own padding. So, if you tried to concatenate two strings without leading or trailing spaces, such as
"hello"."world"
you would get
"helloworld"
as your result.Regardless of the data types of the operands, they are treated as strings, and the result is always a string. We will encounter concatenation frequently throughout this book when we need to combine the results of an expression of some kind with a string, as in
$centimeters = 212;
echo "the width is ".($centimeters/100)." meters";
Combined Assignment Operators
Although there is really only one assignment operator, PHP provides a number of combination operators that transform the left-hand operand and return a result. As a rule, operators use their operands without changing their values, but assignment operators break this rule. A combined assignment operator consists of a standard operator symbol followed by an equal sign. Combination assignment operators save you the trouble of using two operators yourself. For example
$x = 4;
$x = $x + 4; // $x now equals 8
may instead be written as
$x = 4;
$x += 4; // $x now equals 8
There is an assignment operator for each of the arithmetic operators and one for the concatenation operator. Table 4.4 lists some of the most common.
Operator | Example | Equivalent To |
---|---|---|
+= | $x += 5 | $x = $x + 5 |
-= | $x -= 5 | $x = $x - 5 |
/= | $x /= 5 | $x = $x / 5 |
*= | $x *= 5 | $x = $x * 5 |
%= | $x %= 5 | $x = $x % 5 |
.= | $x .= " test" | $x = $x." test" |
Automatically Incrementing and Decrementing an Integer Variable
When coding in PHP, you will often find it necessary to increment or decrement an integer variable. You will usually need to do this when you are counting the iterations of a loop. You have already learned two ways of doing this. We can increment the integer contained by $x with the addition operator
$x = $x + 1; // $x is incremented
or with a combined assignment operator
$x += 1; // $x is incremented
In both cases, the resultant integer is assigned to $x. Because expressions of this kind are so common, PHP provides some special operators that allow you to add or subtract the integer constant 1 from an integer variable, assigning the result to the variable itself. These are known as the post-increment and post-decrement operators. The post-increment operator consists of two plus symbols appended to a variable name:
$x++; // $x is incremented
This expression increments the variable $x by one. Using two minus symbols in the same way decrements the variable:
$x--; // $x is decremented
If you use the post-increment or post-decrement operators in conjunction with a conditional operator, the operand will only be modified after the test has been completed:
$x = 3;
$y = $x++ + 3;
In this instance, $y first becomes 6 (3 + 3) and then $x is incremented.In some circumstances, you might want to increment or decrement a variable in a test expression before the test is carried out. PHP provides the pre-increment and pre-decrement operators for this purpose. These operators behave in exactly the same way as the post-increment and post-decrement operators, but they are written with the plus or minus symbols preceding the variable:
++$x; // $x is incremented
--$x; // $x is decremented
If these operators are used as part of a test expression, the incrementation occurs before the test is carried out.
$x = 3;
++$x < 4; // false
In the previous fragment, $x is incremented before it is tested against 4. The test expression returns false because 4 is not smaller than 4.
Comparison Operators
Comparison operators perform tests on their operands. They return the Boolean value true if the test is successful, or false otherwise. This type of expression is useful in control structures, such as if and while statements. We will cover these in Chapter 5, "Flow Control Functions in PHP."To test whether the value contained in $x is smaller than 5, for example, you can use the less-than operator:
$x < 5
If $x contains the value 3, this expression has the value true. If $x contains 7, the expression resolves to false.Table 4.5 lists the comparison operators.
Creating More Complex Test Expressions with the Logical Operators
The logical operators test combinations of Booleans. For example, the or operator, which is indicated by two pipe characters (||) or simply the word or, returns true if either the left or the right operand is true:
true || false
This expression returns true.The and operator, which is indicated by two ampersand characters (&&) or simply the word and, returns true only if both the left and right operands are true:
true && false
This expression returns false. It's unlikely that you will use a logical operator to test Boolean constants, as it makes more sense to test two or more expressions that resolve to a Boolean. For example
( $x > 2 ) && ( $x < 15 )
returns true if $x contains a value that is greater than 2 and smaller than 15. We include the parentheses to make the code easier to read. Table 4.6 lists the logical operators.
Operator Precedence
When you use an operator, the PHP engine usually reads your expression from left to right. For complex expressions that use more than one operator, though, the waters can become a little murky. First, consider a simple case:
4 + 5
There's no room for confusion here. PHP simply adds 4 to 5. But what about the following fragment?
4 + 5 * 2
This presents a problem. Does it mean the sum of 4 and 5, multiplied by 2, giving the result 18? Or does it mean 4 plus the result of 5 multiplied by 2, resolving to 14? If you were to simply read from left to right, the former would be true. However, PHP attaches different precedence to operators. Because the multiplication operator has higher precedence than the addition operator does, the second solution to the problem is the correct one.You can use parentheses to force PHP to execute the addition expression before the multiplication expression:
(4 + 5) * 2
Whatever the precedence of the operators in a complex expression, it is a good idea to use parentheses to make your code clearer and to save you from obscure bugs. The following is a list of the operators covered in this chapter in precedence order (those with highest precedence are listed first):
++, --, (cast )
/, *, %
+, -
<, <=, =>, >
==, ===, !=
&&
||
=, +=, -=, /=, *=, %=, .=
and
xor
or
As you can see, or has a lower precedence than || and and has a lower precedence than &&, so you can use the lower-precedence logical operators to change the way a complex test expression is read. This is not necessarily a good idea. The following two expressions are equivalent, but the second is much easier to read:
$x and $y || $z
$x && ($y || $z)
Taking it one step further, the following example is easier still:
$x and ($y or $z)
The three examples are all equivalent.The order of precedence is the only reason that both && and and are present in PHP. The same is true of || and or. In most, if not all circumstances, however, use of parentheses will make for clearer code and fewer bugs than code that takes advantage of the difference in precedence of these operators. Throughout this book, we will tend to use the more common || and && operators.