[ Team LiB ] |
![]() ![]() |
Operators and ExpressionsYou can now assign data to variables, and 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 enable you 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 and 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 hour. The combination of operands with an operator to manufacture 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 ) therefore 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 resolves 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. The Assignment OperatorYou 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 operand and assigns it to its left operand, like so: $name = "matt"; The variable $name now contains the string "matt". Interestingly, this construct is an expression. At first glance, it might seem like 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. Arithmetic OperatorsThe arithmetic operators do exactly what you would expect. Table 4.5 lists these operators. The addition operator adds the right operand to the left operand, whereas the subtraction operator subtracts the right operand from the left. The division operator divides the left operand by the right, and the multiplication operator multiplies the left operand by the right. The modulus operator returns the remainder of the left operand divided by the right.
The Concatenation OperatorThe concatenation operator is a single period (.). Treating both operands as strings, it appends the right operand to the left. So "hello"." world" is equivalent to "hello world" Regardless of the data types of the operands, they are treated as strings and the result is always a string. You will encounter concatenation frequently throughout this book when we need to combine the results of an expression of some kind with a string. Here's an example: $centimeters = 212; print "the width is ".($centimeters/100)." meters"; Combined Assignment OperatorsAlthough there is really only one assignment operator, PHP provides a number of combination operators that transform the left operand as well as return a result. As a rule, operators use their operands without changing their values; however, 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 can 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.6 lists some of the most common ones.
Each of the examples in Table 4.6 transforms the value of $x using the value of the right operand. Comparison OperatorsComparison operators perform tests on their operands. They return the boolean value true if the test is successful and return false otherwise. This type of expression is useful in control structures, such as if and while statements. You will meet these in Hour 5. To test whether the value contained in $x is smaller than 5, for example, you would use the less than operator: $x < 5 If $x contained 3, this expression would be equivalent to the value true. If $x contained 7, the expression would resolve to false. Table 4.7 lists the comparison operators.
These operators are most commonly used with integers or doubles, although the equivalence operator is also used to compare strings.
Creating More Complex Test Expressions with the Logical OperatorsThe logical operators test combinations of booleans. The or operator—which is indicated by two pipe characters (||) or simply the characters or—returns true if either the left or the right operand is true. So true || false returns true. The and operator, which is indicated by either two ampersand characters (&&) or the characters and, returns true only if both the left and right operands are true. So true && false returns false. It's unlikely that you would use a logical operator to test boolean constants, however. It would make more sense to test two or more expressions that resolve to a boolean. For example ( $x > 2 ) && ( $x < 15 ) would return true if $x contained a value greater than 2 and smaller than 15. We include the parentheses to make the code easier to read. Table 4.8 lists the logical operators.
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. Automatically Incrementing and Decrementing an Integer VariableWhen coding in PHP, you will often need to increment or decrement an integer variable. You usually need to do this when you are counting the iterations of a loop. You have already learned two ways of doing this. We could increment the integer contained by $x with the addition operator, like so: $x = $x + 1; // $x is incremented Or we could use a combined assignment operator, as shown here: $x += 1; // $x is incremented In both cases, the resultant integer is assigned to $x. Because expressions of this type are so common, PHP provides some special operators that enable you to add or subtract the integer constant 1 from an integer variable and assign 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, as shown in this example: $x++; // $x is incremented This increments the variable $x by one. Using two minus symbols in the same way, we can decrements the variable: $x--; // $x is decremented If you use the post-increment or post-decrement operator in conjunction with a conditional operator, the operand is modified only 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 performed. PHP provides the pre-increment and pre-decrement operators for this purpose. On their own, these operators behave in exactly the same way as the post-increment and post-decrement operators. 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, like so: $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. Operator PrecedenceWhen 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. What about the next fragment? 4 + 5 * 2 This presents a problem. Does it mean the sum of 4 and 5, which should then be multiplied by 2, giving a result of 18? Or, does it mean 4 plus the result of 5 multiplied by 2, resolving to 14? If you were to read simply from left to right, the former would be true. In fact, 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 force PHP to execute the addition expression before the multiplication expression with parentheses: (4 + 5) * 2 Whatever the precedence of the operators in a complex expression, you should use parentheses to make your code clearer and save you from obscure bugs. Table 4.9 lists the operators covered in this hour in precedence order (highest first).
As you can see, or has a lower precedence than || and and has a lower precedence than &&, so you could use the lower-precedence logical operators to change the way a complex test expression is read. This is not necessarily a good idea, however. The following two expressions are equivalent, but the second is much easier to read: $x and $y || $z $x && ($y || $z) ) 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 makes for clearer code and fewer bugs than code that takes advantage of the difference in precedence of these operators. Throughout this book, we will use the more common || and && operators. |
[ Team LiB ] |
![]() ![]() |