An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression).
Operators can be grouped according to the number of values they take.
Operators 'operate' or act on one (unary operators such as
++$a), two (binary operators such as
$a + $b or
$a >> $b) or three (the only ternary operator is
$a ? $b : $c) expressions.
Operator precedence influences how operators are grouped (as if there were parentheses). The following is a list of operators in order of there precendence (operators in the second column). If multiple operators are in one row, the grouping is determined by the code order, where the first column indicates the associativity (see examples).
Full information is at Stack Overflow.
Note that functions and language constructs (e.g.
echo 2 . print 3 + 4; echo's
3 + 4, prints the outcome
7 and returns
1. After that,
2 is echoed, concatenated with the return value of
Altering operator precedence (with parentheses)
The order in which operators are evaluated is determined by the operator precedence (see also the Remarks section).
$a gets a value of 10 because
2 * 3 is evaluated first (multiplication has a higher precedence than addition) yielding a sub-result of
6 + 4, which equals to 10.
The precedence can be altered using parentheses: in
$a gets a value of 14 because
(3 + 4) is evaluated first.
If the preceedence of two operators is equal, the associativity determines the grouping (see also the Remarks section):
% have equal precedence and left associativity. Because the multiplication occurs first (left), it is grouped.
Now, the modulus operator occurs first (left) and is thus grouped.
$b now have value
$b += 1 is grouped and then the result (
2) is assigned to
Basic Assignment (=)
$a having the value
The result of an assignment expression is the value being assigned. Note that a single equal sign
= is NOT for comparison!
does the following:
- Line 1 assigns
- Line 2 assigns
$a. This expression yields value
- Line 2 then assigns the result of the expression in parentheses (
$b now have value
Prefix bitwise operators
Bitwise operators are like logical operators but executed per bit rather than per boolean value.
&: a bit is set only if it is set in both operands
|: a bit is set if it is set in either or both operands
^: a bit is set if it is set in one operand and not set in another operand, i.e. only if that bit is in different state in the two operands
Example uses of bitmasks
These operators can be used to manipulate bitmasks. For example:
| operator is used to combine the two bitmasks. Although
+ has the same effect,
| emphasizes that you are combining bitmasks, not adding two normal scalar integers.
This example (assuming
$option always only contain one bit) uses:
^operator to conveniently toggle bitmasks.
|operator to set a bit neglecting its original state or other bits
~operator to convert an integer with only one bit set into an integer with only one bit not set
&operator to unset a bit, using these properties of
&=with a set bit will not do anything (
(1 & 1) === 1,
(0 & 1) === 0), doing
&=with an integer with only one bit not set will only unset that bit, not affecting other bits.
&=with an unset bit will unset that bit (
(1 & 0) === 0,
(0 & 0) === 0)
- Using the
&operator with another bitmask will filter away all other bits not set in that bitmask.
- If the output has any bits set, it means that any one of the options are enabled.
- If the output has all bits of the bitmask set, it means that all of the options in the bitmask are enabled.
Bear in mind that these comparison operators: (
<=>) have higher precedence than these bitmask-bitmask operators: (
&). As bitwise results are often compared using these comparison operators, this is a common pitfall to be aware of.
Bitwise left shift
<<: shift all bits to the left (more significant) by the given number of steps and discard the bits exceeding the int size
<< $x is equivalent to unsetting the highest
$x bits and multiplying by the
$xth power of 2
Bitwise right shift
>>: discard the lowest shift and shift the remaining bits to the right (less significant)
>> $x is equivalent to dividing by the
$xth power of 2 and discard the non-integer part
Example uses of bit shifting:
Fast division by 16 (better performance than
On 32-bit systems, this discards all bits in the integer, setting the value to 0. On 64-bit systems, this unsets the most significant 32 bits and keep the least
significant 32 bits, equivalent to
$x & 0xFFFFFFFF
Note: In this example,
printf("%'06b") is used. It outputs the value in 6 binary digits.
Combined Assignment (+= etc)
The combined assignment operators are a shortcut for an operation on some variable and subsequently assigning this new value to that variable.
Combined concatenation and assignment of a string:
Combined binary bitwise assignment operators:
For basic equality testing, the equal operator
== is used. For more comprehensive checks, use the identical operator
The identical operator works the same as the equal operator, requiring its operands have the same value, but also requires them to have the same data type.
For example, the sample below will display 'a and b are equal', but not 'a and b are identical'.
When using the equal operator, numeric strings are cast to integers.
Comparison of objects
=== compares two objects by checking if they are exactly the same instance. This means that
new stdClass() === new stdClass() resolves to false, even if they are created in the same way (and have the exactly same values).
== compares two objects by recursively checking if they are equal (deep equals). That means, for
$a == $b, if
- of the same class
- have the same properties set, including dynamic properties
- for each property
$a->property == $b->propertyis true (hence recursively checked).
Other commonly used operators
- Greater Than (
- Lesser Than (
- Greater Than Or Equal To (
- Lesser Than Or Equal To (
- Not Equal To (
- Not Identically Equal To (
- Greater Than:
$a > $b, returns
$a's value is greater than of
$b, otherwise returns false.
- Lesser Than:
$a < $b, returns
$a's value is smaller that of
$b, otherwise returns false.
- Greater Than Or Equal To:
$a >= $b, returns
$a's value is either greater than of
$bor equal to
$b, otherwise returns
- Smaller Than Or Equal To:
$a <= $b, returns
$a's value is either smaller than of
$bor equal to
$b, otherwise returns
5/6. Not Equal/Identical To: To rehash the earlier example on equality, the sample below will display 'a and b are not identical', but not 'a and b are not equal'.
Execution Operator (``)
The PHP execution operator consists of backticks (``) and is used to run shell commands. The output of the command will be returned, and may, therefore, be stored in a variable.
Note that the execute operator and
shell_exec() will give the same result.
Incrementing (++) and Decrementing Operators (--)
Variables can be incremented or decremented by 1 with
--, respectively. They can either precede or succeed variables and slightly vary semantically, as shown below.
More information about incrementing and decrementing operators can be found in the official documentation.
instanceof (type operator)
For checking whether some object is of a certain class, the (binary)
instanceof operator can be used since PHP version 5.
The first (left) parameter is the object to test. If this variable is not an object,
instanceof always returns
false. If a constant expression is used, an error is thrown.
The second (right) parameter is the class to compare with. The class can be provided as the class name itself, a string variable containing the class name (not a string constant!) or an object of that class.
instanceof can also be used to check whether an object is of some class which extends another class or implements some interface:
To check whether an object is not of some class, the not operator (
!) can be used:
Note that parentheses around
$o instanceof MyClass are not needed because
instanceof has higher precedence than
!, although it may make the code better readable with parentheses.
If a class does not exist, the registered autoload functions are called to try to define the class (this is a topic outside the scope of this part of the Documentation!). In PHP versions before 5.1.0, the
instanceof operator would also trigger these calls, thus actually defining the class (and if the class could not be defined, a fatal error would occur). To avoid this, use a string:
As of PHP version 5.1.0, the registered autoloaders are not called anymore in these situations.
Older versions of PHP (before 5.0)
In older versions of PHP (before 5.0), the
is_a function can be used to determine wether an object is of some class. This function was deprecated in PHP version 5 and undeprecated in PHP version 5.3.0.
Logical Operators (&&/AND and ||/OR)
In PHP, there are two versions of logical AND and OR operators.
Note that the
|| opererators have higher precedence than
or. See table below:
|Evaluation||Result of ||Evaluated as|
Because of this it's safer to use
|| instead of
Null Coalescing Operator (??)
Null coalescing is a new operator introduced in PHP 7. This operator returns its first operand if it is set and not
NULL. Otherwise it will return its second operand.
The following example:
is equivalent to both:
This operator can also be chained (with right-associative semantics):
which is an equivalent to:
When using coalescing operator on string concatenation dont forget to use parentheses
This will output
John only, and if its $firstName is null and $lastName is
Doe it will output
Unknown Doe. In order to output
John Doe, we must use parentheses like this.
This will output
John Doe instead of
Object and Class Operators
Members of objects or classes can be accessed using the object operator (
->) and the class operator (
Note that after the object operator, the
$ should not be written (
$object->a instead of
$object->$a). For the class operator, this is not the case and the
$ is necessary. For a constant defined in the class, the
$ is never used.
Also note that
var_dump(MyClass::d()); is only allowed if the function
d() does not reference the object:
This causes a 'PHP Fatal error: Uncaught Error: Using $this when not in object context'
These operators have left associativity, which can be used for 'chaining':
These operators have the highest precedence (they are not even mentioned in the manual), even higher that
The value of
$o1 is added to before the object is cloned!
Note that using parentheses to influence precedence did not work in PHP version 5 and older (it does in PHP 7):
Spaceship Operator (<=>)
PHP 7 introduces a new kind of operator, which can be used to compare expressions. This operator will return -1, 0 or 1 if the first expression is less than, equal to, or greater than the second expression.
Objects are not comparable, and so doing so will result in undefined behaviour.
This operator is particularly useful when writing a user-defined comparison function using
uksort. Given an array of objects to be sorted by their
weight property, for example, an anonymous function can use
<=> to return the value expected by the sorting functions.
In PHP 5 this would have required a rather more elaborate expression.
String Operators (. and .=)
There are only two string operators:
Concatenation of two strings (dot):
Concatenating assignment (dot=):
Ternary Operator (?:)
The ternary operator can be thought of as an inline
if statement. It consists of three parts. The
operator, and two outcomes. The syntax is as follows:
operator is evaluated as
true, the value in the first block will be returned (
<true value>), else the value in the second block will be returned (
<false value>). Since we are setting
$value to the result of our ternary operator it will store the returned value.
$action would contain the string
empty($_POST['action']) evaluates to true. Otherwise it would contain the value of
(expr1) ? (expr2) : (expr3) evaluates to
expr1 evaluates to
It is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3 returns
expr1 evaluates to TRUE, and
?: is often referred to as Elvis operator.
This behaves like the Null Coalescing operator
??, except that
?? requires the left operand to be exactly
?: tries to resolve the left operand into a boolean and check if it resolves to boolean
In this example,
setWidth accepts a width parameter, or default 0, to change the width session value. If
$width is 0 (if
$width is not provided), which will resolve to boolean false, the value of
getDefaultWidth() is used instead. The
getDefaultWidth() function will not be called if
$width did not resolve to boolean false.
Refer to Types for more information about conversion of variables to boolean.