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 can store. 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.
An operator is a symbol or series of symbols that, when used in conjunction with values, performs an action and usually produces a new value. An operand is a value used in conjunction with an operator. There are usually two operands to one operator. |
Let's combine two operands with an operator to produce a new value:
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, though you will see a few exceptions later in this hour.
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, in PHP, an expression 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 subexpressions 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. |
Now that we have the principles out of the way, it's time to take a tour of PHP's more common operators.
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
print ($name = "matt");
prints the string "matt" to the browser in addition to assigning "matt" to $name.
The arithmetic operators do exactly what you would expect?they 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 is represented by a single period. Treating both operands as strings, it appends the right-hand operand to the left. So
"hello"." world"
returns
"hello world"
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.
$centimeters = 212; print "the width is ".($centimeters/100)." meters";
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. Assignment operators break this rule. A combined assignment operator consists of a standard operator symbol followed by an equals 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" |
Each of the examples in Table 4.4 transforms the value of $x using the value of the right-hand operand.
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; $x++ < 4; // true
In the previous example, $x contains 3 when it is tested against 4 with the less than operator, so the test expression returns true. After this test is complete, $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 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 Hour 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.
Operator |
Name |
Returns True If... |
Example ($x is 4) |
Result |
---|---|---|---|---|
== |
Equivalence |
Left is equivalent to right |
$x == 5 |
false |
!= |
Non-equivalence |
Left is not equivalent to right |
$x != 5 |
true |
=== |
Identical |
Left is equivalent to right and they are the same type |
$x === "7" |
false |
> |
Greater than |
Left is greater than right |
$x > 4 |
false |
>= |
Greater than or equal to |
Left is greater than or equal to right |
$x >= 4 |
true |
< |
Less than |
Left is less than right |
$x < 4 |
false |
<= |
Less than or equal to |
Left is less than or equal to right |
$x <= 4 |
true |
These operators are most commonly used with integers or doubles, although the equivalence operator is also used to compare strings. Be very sure you understand the difference between the == and = operators. The == operator tests equivalence, while the = operator assigns value.
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, only returns true 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, however. 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 |
Name |
Returns True If... |
Example |
Result |
---|---|---|---|---|
|| |
Or |
Left or right is true |
true || false |
true |
or |
Or |
Left or right is true |
true or false |
true |
xor |
Xor |
Left or right is true but not both |
true xor true |
false |
&& |
And |
Left and right are true |
true && false |
false |
and |
And |
Left and right are true |
true and false |
false |
! |
Not |
The single operand is not true |
! true |
false |
Why are there two versions of both the or and the and operators? The answer lies in operator precedence, which we will look at later in this section.
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 hour 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.