Operators and Expressions
what you have learned so far, you can 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 have stored.Operators are symbols used to manipulate data stored in variables, to make it possible to use one or more values to produce a new value, or to check the validity of data to determine the next step in a condition, and so forth. A value that is operated on by an operator is referred to as an operand.
By the Way
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 or more operands to one operator.
In this simple example, two operands are combined with an operator to produce a new value:
(4 + 5)
The integers 4 and 5 are operands. These operands are operated on by the addition operator (+), to produce the integer 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 operators and their operands 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(). The expression (4 + 5), for example, consists of two expressions (4 and 5) 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. In this case, the expression (4 + 5) resolves to 9.
By the way
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 the operators commonly used in PHP programming.
The Assignment Operator
You have seen the assignment operator in use each time a variable was declared in an example; the assignment operator consists of the single character: =.The assignment operator takes the value of the right-hand operand and assigns it to the left-hand operand:
$name = “jimbo”;
The variable $name now contains the string “jimbo”. This construct is also an expression; while it may seem at first glance that the assignment operator simply changes the variable $name without producing a value, in fact, a statement that uses the assignment operator always resolves to a copy of the value of the right operand. Thus
echo $name = “jimbo”;
prints the string “jimbo” to the browser while it also assigns the value “jimbo” to the $name variable.
The arithmetic operators do exactly what you would expectthey perform arithmetic operations. Table 5.2 lists these operators along with examples of their usage and results.
Table 5.2. Arithmetic Operators Operator
The addition operator adds the right-hand operand to the left-hand operand. The subtraction operator subtracts the right-hand operand from the left-hand operand. The division operator divides the left-hand operand by the right-hand operand. The multiplication operator multiplies the left-hand operand by the right-hand operand. The modulus operator returns the remainder of the left-hand operand divided by the right-hand operand.
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-hand operand. So
Note that the resulting space between the words occurs because there is a leading space in the second operand (“world” instead of “world”). The concatenation operator literally smashes together two strings without adding any padding. So, if you tried to concatenate two strings without leading or trailing spaces, such as
you would get this as your result:
Regardless of the data types of the operands used with the concatenation operator, they are treated as strings, and the result will always be of the string type. 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
$cm = 212;
echo “the width is “.($cm/100).” meters”;
Combined Assignment Operators
Although there is only one true assignment operator, PHP provides a number of combination operators that transform the left-hand operand and return a result, while also modifying the original value of the variable. As a rule, operators use operands but do not change their original values, but combined 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 in two different steps within your script. For example,
if you have a variable with a value of 4, and you want to increase this value to 4 more, you might see:
$x = 4;
$x = $x + 4; // $x now equals 8
However, you can also use a combination assignment operator (+=) to add and return the new value, as shown here:
$x = 4;
$x += 4; // $x now equals 8
Each arithmetic operator, as well as the concatenation operator, also has a corresponding combination assignment operator. Table 5.3 lists these new operators and shows an example of their usage.
Table 5.3. Some Combined Assignment Operators Operator
$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 5.3 transforms the value of $x using the value of the right-hand operand. Subsequent uses of $x will refer to the new value. For example
$x = 4;
$x += 4; // $x now equals 8
$x += 4; // $x now equals 12
$x -= 3; // $x now equals 9
These operators will be used throughout the scripts in the book. You will frequently see the combined concatenation assignment operator when you begin to create dynamic text; looping through a script and adding content to a string, such as dynamically building the HTML code to represent a table, is a prime example of the use of a combined assignment operator.
Automatically Incrementing and Decrementing an Integer Variable
When coding in PHP, you will often find it necessary to increment or decrement a variable that is an “integer” type. You will usually need to do this when you are counting the iterations of a loop. You have already learned two ways of doing thisincrementing the value of $x using the addition operator
$x = $x + 1; // $x is incremented by 1
or by using a combined assignment operator
$x += 1; // $x is incremented by 1
In both cases, the new value is assigned to $x. Because expressions of this kind are 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 by 1
This expression increments the value represented by the variable $x, by one. Using two minus symbols in the same way will decrement the variable:
$x–; // $x is decremented by 1
If you use the post-increment or post-decrement operators in conjunction with a conditional operator, the operand will only be modified after the first operation has finished:
$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 by 1
–$x; // $x is decremented by 1
If these operators are used as part of a test expression, the incrementation occurs before the test is carried out. For example, in the next fragment, $x is incremented before it is tested against 4.
$x = 3;
++$x < 4; // false
The test expression returns false because 4 is not smaller than 4.
Comparison operators perform comparative tests using their operands and return the Boolean value TRue if the test is successful, or false if the test fails. This type of expression is useful when using control structures in your scripts, such as if and while statements. We will cover if and while statements in Chapter 6, “Flow Control Functions in PHP.”
For example, to test whether the value contained in $x is smaller than 5, you can use the less-than operator as part of your expression:
$x < 5
If $x contains the value 3, this expression will have the value true. If $x contains 7, the expression resolves to false.
Table 5.4 lists the comparison operators.
Table 5.4. Comparison Operators Operator
Returns True If…
Example ($x Is 4)
Left is equivalent to right
$x == 5
Left is not equivalent
$x != 5
$x === 4
Left is equivalent to right and they are the same type
Left is equivalent to right but they are not the same type
$x === “4”
Left is greater than right
$x > 4
Greater than or equal to
Left is greater than or equal to right
$x >= 4
Left is less than right
Less than or equal to
Left is less than or equal to right
These operators are most commonly used with integers or doubles, although the equivalence operator is also used to compare strings. Be very sure to understand the difference between the == and = operators. The == operator tests equivalence, whereas the = operator assigns value. Also, remember that === tests equivalence with regards to both value and type.
Creating Complex Test Expressions with the Logical Operators
Logical operators test combinations of Boolean values. For example, the or operator, which is indicated by two pipe characters (||) or simply the word or, returns the Boolean value 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 the Boolean value true only if both the left and right operands are true:
true && false
This expression returns the Boolean value false. It’s unlikely that you will use a logical operator to test Boolean constants, because it makes more sense to test two or more expressions that resolve to a Boolean. For example
($x > 2) && ($x < 15)
returns the Boolean value TRue if $x contains a value that is greater than 2 and smaller than 15. Parentheses are used when comparing expressions in order to make the code easier to read, and to indicate the precedence of expression evaluation. Table 5.5 lists the logical operators.
Table 5.5. Logical Operators Operator
Returns True If…
Left or right is true
true || false
Left or right is true
true or false
Left or right is true but not both
true xor true
Left and right are true
true && false
Left and right are true
TRue and false
The single operand is not true
You may wonder why are there two versions of both the or and the and operators, and that’s a good question. The answer lies in operator precedence, which we will look at next.
When you use an operator within an expression, the PHP engine usually reads your expression from left to right. For complex expressions that use more than one operator, though, the PHP engine could be led astray without some guidance. First, consider a simple case:
4 + 5
There’s no room for confusion herePHP simply adds 4 to 5. But what about the following fragment, with two operators:
4 + 5 * 2
This presents a problem. Should PHP find the sum of 4 and 5, then multiply it by 2, providing 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 different operators, and because the multiplication operator has higher precedence than the addition operator, the second solution to the problem is the correct one: 4 plus the result of 5 multiplied by 2.
However, you can override operator precedence by putting parentheses around your expressions; in the following fragment, the addition expression will now be evaluated 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 bugs such as applying sales tax to the wrong subtotal in a shopping cart situation. The following is a list of the operators covered in this chapter in precedence order (those with highest precedence are listed first):
++, –, (cast)
/, *, %
<, <=, =>, >
==, ===, !=
=, +=, -=, /=, *=, %=, .=
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. In the following fragment, the 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 fragment is easier still:
$x and ($y or $z)
However, all three examples are equivalent.
The order of precedence is the only reason that both && and and are available in PHP. The same is true of || and or. In most circumstances, the 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, and rely on parenthetical statements to set specific operator precedence.
آموزش برنامه نویسی طراحی سایت اختصاصی یا آموزش اختصاصی طراحی وب سایت برای دانشجویان رشته های مهندسی کامپیوتر و فناوری اطلاعات و سایر دانشجویان و علاقه مندان به صنعت طراحی سایت ، برای تهیه بسته آموزش طراحی سایت به mortezasaheb.ir مراجعه نمایید
ارایه درگاه پرداخت ePayBank.ir برای پروژه ها و برنامه های تحت وب PHP
تبلیغات نیازمندی سایت و وبلاگ یا محصولات فروشگاهی خویش را در MyCityAd.ir درج آگهی کنید.