PHP Operators

As their name subtly suggests, operators are the catalysts of operations. There are many types of operators in PHP, those commonly used are:

• Assignment Operators for assigning data to variables
• Arithmetic Operators for performing basic math functions
• String Operators for joining two or more strings
• Comparison Operators for comparing two pieces of data
• Logical Operators for performing logical operations on Boolean values

In addition, PHP also provides:
• Bitwise Operators for manipulating bits using boolean math
• Error Control Operators for suppressing errors
• Execution Operators for executing system commands
• Incrementing/Decrementing Operators for incrementing and decrementing numerical values
• Type Operators for identifying Objects

Arithmetic Operators
Arithmetic operators allow you to perform basic mathematical operations:

Addition $a = 1 + 3.5;
Subtraction $a = 4 - 2;
Multiplication $a = 8 * 3;
Division $a = 15 / 5;
Modulus $a = 23 % 7;

Incrementing/decrementing operators are a special category of operators that make it possible to increment or decrement the value of an integer by one. They are unary operators, because they only accept one operand (that is, the variable that needs to be incremented or decremented), and are somewhat of an oddity, in that their behavior changes depending on whether they are appended or prepended to their operand.

The position of the operator determines whether the adjustment it performs takes place prior to, or after returning the value:

• If the operator is placed after its operand, the interpreter will first return the value of the latter
  (unchanged), and then either increment or decrement it by one.
• If the operator is placed before the operand, the interpreter will first increment or decrement the
  value of the latter, and then return the newly-calculated value.

Here are a few examples:

$a = 1;
// Assign the integer 1 to $a
echo $a++;
// Outputs 1, $a is now equal to 2
echo ++$a;
// Outputs 3, $a is now equal to 3
echo --$a;
// Outputs 2, $a is now equal to 2
echo $a--;
// Outputs 2, $a is now equal to 1

The String Concatenation Operator
Unlike many other languages, PHP has a special operation that can be used to glue—or, more  properly, concatenate—two strings together:

$string = "foo" . "bar";
// $string now contains the value 'foobar'

Bitwise Operators
Bitwise operators allow you to manipulate bits of data. All these operators are designed to work only on integer numbers—therefore, the interpreter will attempt to convert their operands to integers before executing them.

The simplest bitwise operator is binary not, which negates all the bits of an integer number:

$x = 0;
echo ~$x; // will output -1

A group of binary bitwise operators is used to perform basic bit manipulation by combining the bits of its two operands in various ways:

& Bitwise AND. The result of the operation will be a value whose bits are set if they are set
in both  operands, and unset otherwise.
| Bitwise OR. The result of the operation will be a value whose bits are set if they are set
in either  operand (or both), and unset otherwise.
ˆ Bitwise XOR (exclusive OR). The result of the operation will be a value whose bits are set
if they are set in either operand, and unset otherwise.

A third set of operators is used to shift bits left or right:

<< Bitwise left shift. This operation shifts the left-hand operand's bits to the left by a
number of  positions equal to the right operand, inserting unset bits in the shifted positions.
>> Bitwise right shift. This operation shifts the left-hand operand's bits to the right by a
number of positions equal to the right operand, inserting unset bits in the shifted positions.

It’s interesting to note that these last two operations provide an easy (and very fast) way of multiplying integers by a power of two. For example:

$x = 1;
echo $x << 1; // Outputs 2
echo $x << 2; // Outputs 4
$x = 8;
echo $x >> 1; // Outputs 4
echo $x >> 2; // Outputs 2

Assignment Operators
Given the creativity that we have shown in the naming conventions to this point, you’ll probably be very surprised to hear that assignment operators make it possible to assign a value to a variable. The simplest assignment operator is a single equals sign, which we have already seen in previous examples:

$variable = 'value';
// $variable now contains the string 'value'

In addition, it is possible to combine just about every other type of binary arithmetic and bitwise operator with the = sign to simultaneously perform an operation on a variable and reassign the resulting value to itself:

$variable = 1;
// $variable now contains the integer value 1
$variable += 3;
$variable now contains the integer 4

In this example, we pair the addition operator (the plus sign) with the equals sign to add the existing value of $variable to the right operand, the integer 3. This technique can be used with all binary arithmetic and bitwise operators.

Referencing Variables
By default, assignment operators work by value—that is, they copy the value of an expression on to another. If the right-hand operand happens to be a variable, only its value is copied, so that any subsequent change to the left-hand operator is not reflected in the right-hand one. For example:

$a = 10;
$b = $a;
$b = 20;
echo $a; // Outputs 10

Naturally, you expect this to be the case, but there are circumstances in which you may want an assignment to take place by reference, so that the left-hand operand becomes “connected” with the right-hand one:

$a = 10;
$b = &$a; // by reference
$b = 20;
echo $a; // Outputs 20

Comparison Operators
Comparison operations are binary operations that establish a relationship of equivalence between two values. They can either establish whether two values are equal (or not equal) to each other, and whether one is greater (or smaller) than the other.
The result of a comparison operation is always a Boolean value.

There are four equivalence operations:

== Equivalence. Evaluates to true if the two operands are equivalent, meaning that they can
be converted to a common data type in which they have the same value but are not necessarily 
of the same type.
===  Identity. Evaluates to true only if the operands are of the same data type and have the
same value.
!=  Not-equivalent operator. Evaluates to true if the two operands are not equivalent, without
regards to their data type.
!==  Not-identical operator. Evaluates to true if the two operands are not of the same data
type or do not have the same value.

These two operations are completely identical—but, because the left-hand operator of an assignment must be a variable, if you had forgotten one of the equal signs, the parser would have thrown an error, thus alerting you to your mistake.

A different set of operators establishes a relationship of inequality between two operands—that is, whether one of the two is greater than the other:

< and <= Evaluates to true if the left operand is less than, or less than or equal to the
right operand.
> and >= Evaluates to true if the left operand is greater than or greater than or equal to the
right operand.

Logical Operators
Logical operators are used to connect together Boolean values and obtain a third Boolean value depending on the first two. There are four logical operators in PHP, of which three are binary. The only unary operator is the Logical NOT, identified by a single exclamation point that precedes its operand:

$a = false;
echo !$a; // outputs 1 (true)

It’s important to understand that all logical operators onlywork with Boolean values; therefore, PHP will first convert any other value to a Boolean and then perform the operation.

The three binary operators are:
&& / and The AND operator evaluates to true if both the left and right operands evaluate to true.
The most commonly-used form of this operator is &&.
|| / or The OR operator evaluates to true if either the left or right operands evaluate to true,
with the || form being more commonly used.
XOR The Exclusive OR operator evaluates to true if either the left and right operands evaluates
to true, but not both.

It’s important to understand that PHP employs a very simple shortcut strategy when executing binary logical operations. For example, if the left-hand side operand of an AND operation evaluates to false, then the operation returns false immediately (since any other result would be impossible), without evaluating the right-hand side operand at all.

In addition to improving performance, this approach is a lifesaver in many situations where you actually don’t want the right-hand operand to be evaluated at all, based on the first one.

Other Operators
In addition to all the operators we’ve seen this far, PHP also uses a few specialized operators to simplify certain tasks. One of these is the error suppression operator @; when prepended to an expression, this operator causes PHP to ignore almost all error messages that occur while that expression is being evaluated:

$x = @mysql_connect();

The code above will prevent the call to mysql_connect() from outputting an error— provided that the function uses PHP’s own functionality for reporting errors.
Sadly, some libraries output their errors directly, bypassing PHP and, therefore, make it much harder to manage with the error-control operator.
The backtick operator makes it possible to execute a shell command and retrieve its output.

For example, the following will cause the output of the UNIX ls command to be stored inside $a:

$a = `ls -l`;

Operator Precedence and Associativity
As we have all learned in school, not all operations have the same precedence. When using an infix notation, the order in which operations are written in an expression lends itself to a certain amount of ambiguitywhichmust, therefore, be resolved.

This can be done in one of two ways:
using parentheses to indicate which operations should be performed first, or by using a set of pre-defined precedence rules.

Even if we establish the precedence of each operation, however, we lack one important
tool: how do we decide in which order we execute operations that have the
same precedence? This is determined by an operation’s associativity, which can either
be left (operations are performed left-to-right), right (operations are performed
right-to-left) or none (for operations that cannot be associated).

The following table illustrates the precedence and associativity of each operation:

Associativity Operator

left [
non-associative ++ -
non-associative ! ˜ - (int) (float) (string) (array) (object) @
left * / %
left + - .
left << >>
non-associative < <= > >=
non-associative == != === !==
left &
left ˆ
left |
left &&
left ||
left ? :
right = += -= *= /= .= %= &= |= ˆ= <<= >>=
left and
left xor
left or
left ,

Next Topic | Previous Topic

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

Leave a Comment

Your email address will not be published. Required fields are marked *