# PHP Crash Course

• Print
This chapter is from the book

## Using Operators

Operators are symbols that you can use to manipulate values and variables by performing an operation on them. You need to use some of these operators to work out the totals and tax on the customer’s order.

We’ve already mentioned two operators: the assignment operator (=) and the string concatenation operator (.). In the following sections, we describe the complete list.

In general, operators can take one, two, or three arguments, with the majority taking two. For example, the assignment operator takes two: the storage location on the left side of the = symbol and an expression on the right side. These arguments are called operands—that is, the things that are being operated upon.

### Arithmetic Operators

Arithmetic operators are straightforward; they are just the normal mathematical operators. PHP’s arithmetic operators are shown in Table 1.1.

#### Table 1.1 PHP’s Arithmetic Operators

 Operator Name Example + Addition \$a + \$b - Subtraction \$a - \$b * Multiplication \$a * \$b / Division \$a / \$b % Modulus \$a % \$b

With each of these operators, you can store the result of the operation, as in this example:

`\$result = \$a + \$b;`

Addition and subtraction work as you would expect. The result of these operators is to add or subtract, respectively, the values stored in the \$a and \$b variables.

You can also use the subtraction symbol (-) as a unary operator—that is, an operator that takes one argument or operand—to indicate negative numbers, as in this example:

`\$a = -1;`

Multiplication and division also work much as you would expect. Note the use of the asterisk as the multiplication operator rather than the regular multiplication symbol, and the forward slash as the division operator rather than the regular division symbol.

The modulus operator returns the remainder calculated by dividing the \$a variable by the \$b variable. Consider this code fragment:

`\$a = 27;\$b = 10;\$result = \$a%\$b;`

The value stored in the \$result variable is the remainder when you divide 27 by 10—that is, 7.

You should note that arithmetic operators are usually applied to integers or doubles. If you apply them to strings, PHP will try to convert the string to a number. If it contains an e or an E, it will be read as being in scientific notation and converted to a float; otherwise, it will be converted to an integer. PHP will look for digits at the start of the string and use them as the value; if there are none, the value of the string will be zero.

### String Operators

You’ve already seen and used the only string operator. You can use the string concatenation operator to add two strings and to generate and store a result much as you would use the addition operator to add two numbers:

`\$a = "Bob's ";\$b = "Auto Parts";\$result = \$a.\$b;`

The \$result variable now contains the string "Bob's Auto Parts".

### Assignment Operators

You’ve already seen the basic assignment operator (=). Always refer to this as the assignment operator and read it as “is set to.” For example,

`\$totalqty = 0;`

This line should be read as “\$totalqty is set to zero.” We explain why when we discuss the comparison operators later in this chapter, but if you call it equals, you will get confused.

#### Values Returned from Assignment

Using the assignment operator returns an overall value similar to other operators. If you write

`\$a + \$b`

the value of this expression is the result of adding the \$a and \$b variables together. Similarly, you can write

`\$a = 0;`

The value of this whole expression is zero.

This technique enables you to form expressions such as

`\$b = 6 + (\$a = 5);`

This line sets the value of the \$b variable to 11. This behavior is generally true of assignments: The value of the whole assignment statement is the value that is assigned to the left operand.

When working out the value of an expression, you can use parentheses to increase the precedence of a subexpression, as shown here. This technique works exactly the same way as in mathematics.

#### Combined Assignment Operators

In addition to the simple assignment, there is a set of combined assignment operators. Each of them is a shorthand way of performing another operation on a variable and assigning the result back to that variable. For example,

`\$a += 5;`

This is equivalent to writing

`\$a = \$a + 5;`

Combined assignment operators exist for each of the arithmetic operators and for the string concatenation operator. A summary of all the combined assignment operators and their effects is shown in Table 1.2.

#### Table 1.2 PHP’s Combined Assignment Operators

 Operator Use Equivalent To += \$a += \$b \$a = \$a + \$b -= \$a -= \$b \$a = \$a - \$b *= \$a *= \$b \$a = \$a * \$b /= \$a /= \$b \$a = \$a / \$b %= \$a %= \$b \$a = \$a % \$b .= \$a .= \$b \$a = \$a . \$b

#### Pre- and Post-Increment and Decrement

The pre- and post-increment (++) and decrement (--) operators are similar to the += and -= operators, but with a couple of twists.

All the increment operators have two effects: They increment and assign a value. Consider the following:

`\$a=4;echo ++\$a;`

The second line uses the pre-increment operator, so called because the ++ appears before the \$a. This has the effect of first incrementing \$a by 1 and second, returning the incremented value. In this case, \$a is incremented to 5, and then the value 5 is returned and printed. The value of this whole expression is 5. (Notice that the actual value stored in \$a is changed: It is not just returning \$a + 1.)

If the ++ is after the \$a, however, you are using the post-increment operator. It has a different effect. Consider the following:

`\$a=4;echo \$a++;`

In this case, the effects are reversed. That is, first, the value of \$a is returned and printed, and second, it is incremented. The value of this whole expression is 4. This is the value that will be printed. However, the value of \$a after this statement is executed is 5.

As you can probably guess, the behavior is similar for the -- (decrement) operator. However, the value of \$a is decremented instead of being incremented.

#### Reference Operator

The reference operator (&, an ampersand) can be used in conjunction with assignment. Normally, when one variable is assigned to another, a copy is made of the first variable and stored elsewhere in memory. For example,

`\$a = 5;\$b = \$a;`

These code lines make a second copy of the value in \$a and store it in \$b. If you subsequently change the value of \$a, \$b will not change:

`\$a = 7; // \$b will still be 5`

You can avoid making a copy by using the reference operator. For example,

`\$a = 5;\$b = &\$a;\$a = 7; // \$a and \$b are now both 7`

References can be a bit tricky. Remember that a reference is like an alias rather than like a pointer. Both \$a and \$b point to the same piece of memory. You can change this by unsetting one of them as follows:

`unset(\$a);`

Unsetting does not change the value of \$b (7) but does break the link between \$a and the value 7 stored in memory.

### Comparison Operators

The comparison operators compare two values. Expressions using these operators return either of the logical values true or false depending on the result of the comparison.

#### The Equal Operator

The equal comparison operator (==, two equal signs) enables you to test whether two values are equal. For example, you might use the expression

`\$a == \$b`

to test whether the values stored in \$a and \$b are the same. The result returned by this expression is true if they are equal or false if they are not.

You might easily confuse == with =, the assignment operator. Using the wrong operator will work without giving an error but generally will not give you the result you wanted. In general, nonzero values evaluate to true and zero values to false. Say that you have initialized two variables as follows:

`\$a = 5;\$b = 7;`

If you then test \$a = \$b, the result will be true. Why? The value of \$a = \$b is the value assigned to the left side, which in this case is 7. Because 7 is a nonzero value, the expression evaluates to true. If you intended to test \$a == \$b, which evaluates to false, you have introduced a logic error in your code that can be extremely difficult to find. Always check your use of these two operators and check that you have used the one you intended to use.

Using the assignment operator rather than the equals comparison operator is an easy mistake to make, and you will probably make it many times in your programming career.

#### Other Comparison Operators

PHP also supports a number of other comparison operators. A summary of all the comparison operators is shown in Table 1.3. One to note is the identical operator (===), which returns true only if the two operands are both equal and of the same type. For example, 0=='0' will be true, but 0==='0' will not because one zero is an integer and the other zero is a string.

#### Table 1.3 PHP’s Comparison Operators

 Operator Name Use == Equals \$a == \$b === Identical \$a === \$b != Not equal \$a != \$b !== Not identical \$a !== \$b <> Not equal (comparison operator) \$a <> \$b << Less than \$a < \$b >

Greater than (comparison operator) \$a > \$b <= Less than or equal to \$a <= \$b >= Greater than or equal to \$a >= \$b

### Logical Operators

The logical operators combine the results of logical conditions. For example, you might be interested in a case in which the value of a variable, \$a, is between 0 and 100. You would need to test both the conditions \$a >= 0 and \$a <= 100, using the AND operator, as follows:

`\$a >= 0 && \$a <=100`

PHP supports logical AND, OR, XOR (exclusive or), and NOT.

The set of logical operators and their use is summarized in Table 1.4.

#### Table 1.4 PHP’s Logical Operators

 Operator Name Use Result ! NOT !\$b Returns true if \$b is false and vice versa && AND \$a && \$b Returns true if both \$a and \$b are true; otherwise false || OR \$a || \$b Returns true if either \$a or \$b or both are true; otherwise false and AND \$a and \$b Same as &&, but with lower precedence or OR \$a or \$b Same as ||, but with lower precedence xor XOR \$a x or \$b Returns true if either \$a or \$b is true, and false if they are both true or both false.

The and and or operators have lower precedence than the && and || operators. We cover precedence in more detail later in this chapter.

### Bitwise Operators

The bitwise operators enable you to treat an integer as the series of bits used to represent it. You probably will not find a lot of use for the bitwise operators in PHP, but a summary is shown in Table 1.5.

#### Table 1.5 PHP’s Bitwise Operators

 Operator Name Use Result & Bitwise AND \$a & \$b Bits set in \$a and \$b are set in the result. | Bitwise OR \$a | \$b Bits set in \$a or \$b are set in the result. ~ Bitwise NOT ~\$a Bits set in \$a are not set in the result and vice versa. ^ Bitwise XOR \$a ^ \$b Bits set in \$a or \$b but not in both are set in the result. << Left shift \$a << \$b Shifts \$a left \$b bits. >> Right shift \$a >> \$b Shifts \$a right \$b bits.

### Other Operators

In addition to the operators we have covered so far, you can use several others.

The comma operator (,) separates function arguments and other lists of items. It is normally used incidentally.

Two special operators, new and ->, are used to instantiate a class and access class members, respectively. They are covered in detail in Chapter 6.

There are a few others that we discuss briefly here.

#### The Ternary Operator

The ternary operator (?:) takes the following form:

`condition ? value if true : value if false`

This operator is similar to the expression version of an if-else statement, which is covered later in this chapter.

A simple example is

`(\$grade >= 50 ? 'Passed' : 'Failed')`

This expression evaluates student grades to 'Passed' or 'Failed'.

#### The Error Suppression Operator

The error suppression operator (@) can be used in front of any expression—that is, anything that generates or has a value. For example,

`\$a = @(57/0);`

Without the @ operator, this line generates a divide-by-zero warning. With the operator included, the error is suppressed.

If you are suppressing warnings in this way, you need to write some error handling code to check when a warning has occurred. If you have PHP set up with the track_errors feature enabled in php.ini, the error message will be stored in the global variable \$php_errormsg.

#### The Execution Operator

The execution operator is really a pair of operators—a pair of backticks (``) in fact. The backtick is not a single quotation mark; it is usually located on the same key as the ~ (tilde) symbol on your keyboard.

PHP attempts to execute whatever is contained between the backticks as a command at the server’s command line. The value of the expression is the output of the command.

For example, under Unix-like operating systems, you can use

`\$out = `ls -la`;echo '<pre>'.\$out.'</pre>';`

Or, equivalently on a Windows server, you can use

`\$out = `dir c:`;echo '<pre>'.\$out.'</pre>';`

Either version obtains a directory listing and stores it in \$out. It can then be echoed to the browser or dealt with in any other way.

There are other ways of executing commands on the server. We cover them in Chapter 17, “Interacting with the File System and the Server.”

#### Array Operators

There are a number of array operators. The array element operators ([]) enable you to access array elements. You can also use the => operator in some array contexts. These operators are covered in Chapter 3.

You also have access to a number of other array operators. We cover them in detail in Chapter 3 as well, but we included them here in Table 1.6 for completeness.

#### Table 1.6 PHP’s Array Operators

 Operator Name Use Result + Union \$a + \$b Returns an array containing everything in \$a and \$b == Equality \$a == \$b Returns true if \$a and \$b have the same key and value pairs === Identity \$a === \$b Returns true if \$a and \$b have the same key and value pairs in the same order and of the same type. != Inequality \$a != \$b Returns true if \$a and \$b are not equal <> Inequality \$a <> \$b Returns true if \$a and \$b are not equal !== Non-identity \$a !== \$b Returns true if \$a and \$b are not identical

You will notice that the array operators in Table 1.6 all have equivalent operators that work on scalar variables. As long as you remember that + performs addition on scalar types and union on arrays—even if you have no interest in the set arithmetic behind that behavior—the behaviors should make sense. You cannot usefully compare arrays to scalar types.

#### The Type Operator

There is one type operator: instanceof. This operator is used in object-oriented programming, but we mention it here for completeness. (Object-oriented programming is covered in Chapter 6.)

The instanceof operator allows you to check whether an object is an instance of a particular class, as in this example:

`class sampleClass{};\$myObject = new sampleClass();if (\$myObject instanceof sampleClass)  echo  "myObject is an instance of sampleClass";`