# Operators

## Introduction

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.

## Remarks

Operators 'operate' or act on one (unary operators such as `!\$a` and `++\$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).

AssociationOperator
left`->` `::`
none`clone` `new`
left`[`
right`**`
right`++` `--` `~` `(int)` `(float)` `(string)` `(array)` `(object)` `(bool)` `@`
none`instanceof`
right`!`
left`*` `/` `%`
left`+` `-` `.`
left`<<` `>>`
none`<` `<=` `>` `>=`
none`==` `!=` `===` `!==` `<>` `<=>`
left`&`
left`^`
left`|`
left`&&`
left`||`
right`??`
left`? :`
right`=` `+=` `-=` `*=` `**=` `/=` `.=` `%=` `&=` `
left`and`
left`xor`
left`or`

Full information is at Stack Overflow.

Note that functions and language constructs (e.g. `print`) are always evaluated first, but any return value will be used according to the above precedence/associativity rules. Special care is needed if the parentheses after a language construct are omitted. E.g. `echo 2 . print 3 + 4;` echo's `721`: the `print` part evaluates `3 + 4`, prints the outcome `7` and returns `1`. After that, `2` is echoed, concatenated with the return value of `print` (`1`).

## Altering operator precedence (with parentheses)

The order in which operators are evaluated is determined by the operator precedence (see also the Remarks section).

In

`\$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.

# Left association

If the preceedence of two operators is equal, the associativity determines the grouping (see also the Remarks section):

`*` and `%` 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.

# Right association

Both `\$a` and `\$b` now have value `2` because `\$b += 1` is grouped and then the result (`\$b` is `2`) is assigned to `\$a`.

## Basic Assignment (=)

results in `\$a` having the value `some string`.

The result of an assignment expression is the value being assigned. Note that a single equal sign `=` is NOT for comparison!

does the following:

1. Line 1 assigns `3` to `\$a`.
2. Line 2 assigns `5` to `\$a`. This expression yields value `5` as well.
3. Line 2 then assigns the result of the expression in parentheses (`5`) to `\$b`.

Thus: both `\$a` and `\$b` now have value `5`.

# Prefix bitwise operators

Bitwise operators are like logical operators but executed per bit rather than per boolean value.

Bitwise AND `&`: a bit is set only if it is set in both operands

Bitwise OR `|`: a bit is set if it is set in either or both operands

Bitwise XOR `^`: 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

These operators can be used to manipulate bitmasks. For example:

Here, the `|` 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:

• the `^` operator to conveniently toggle bitmasks.
• the `|` operator to set a bit neglecting its original state or other bits
• the `~` operator to convert an integer with only one bit set into an integer with only one bit not set
• the `&` operator to unset a bit, using these properties of `&`:
• Since `&=` 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.

# Bit-shifting operators

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 `\$x`th 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 `\$x`th power of 2 and discard the non-integer part

## Example uses of bit shifting:

Fast division by 16 (better performance than `/= 16`)

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.

Arithmetic:

Processing Multiple Arrays Together

Combined concatenation and assignment of a string:

Combined binary bitwise assignment operators:

# Equality

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 `\$a` and `\$b` are:

1. of the same class
2. have the same properties set, including dynamic properties
3. for each property `\$property` set, `\$a->property == \$b->property` is true (hence recursively checked).

# Other commonly used operators

They include:

1. Greater Than (`>`)
2. Lesser Than (`<`)
3. Greater Than Or Equal To (`>=`)
4. Lesser Than Or Equal To (`<=`)
5. Not Equal To (`!=`)
6. Not Identically Equal To (`!==`)
1. Greater Than: `\$a > \$b`, returns `true` if `\$a`'s value is greater than of `\$b`, otherwise returns false.

Example:

1. Lesser Than: `\$a < \$b`, returns `true` if `\$a`'s value is smaller that of `\$b`, otherwise returns false.

Example:

1. Greater Than Or Equal To: `\$a >= \$b`, returns `true` if `\$a`'s value is either greater than of `\$b` or equal to `\$b`, otherwise returns `false`.

Example:

1. Smaller Than Or Equal To: `\$a <= \$b`, returns `true` if `\$a`'s value is either smaller than of `\$b` or equal to `\$b`, otherwise returns `false`.

Example:

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 `++` or `--`, respectively. They can either precede or succeed variables and slightly vary semantically, as shown below.

## 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.

# Caveats

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.

OperatorTrue if
`\$a and \$b`Both `\$a` and `\$b` are true
`\$a && \$b`Both `\$a` and `\$b` are true
`\$a or \$b`Either `\$a` or `\$b` is true
`\$a || \$b`Either `\$a` or `\$b` is true

Note that the `&&` and `||` opererators have higher precedence than `and` and `or`. See table below:

EvaluationResult of `\$e`Evaluated as
`\$e = false || true`True`\$e = (false || true)`
`\$e = false or true`False`(\$e = false) or true`

Because of this it's safer to use `&&` and `||` instead of `and` and `or`.

## 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:

and:

This operator can also be chained (with right-associative semantics):

which is an equivalent to:

Note:
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 `John` only.

## 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 `clone`. Thus:

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 `usort`, `uasort`, or `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:

If the `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.

Example:

`\$action` would contain the string `'default'` if `empty(\$_POST['action'])` evaluates to true. Otherwise it would contain the value of `\$_POST['action']`.

The expression `(expr1) ? (expr2) : (expr3)` evaluates to `expr2` if `expr1`evaluates to `true`, and `expr3` if `expr1` evaluates to `false`.

It is possible to leave out the middle part of the ternary operator. Expression `expr1 ?: expr3` returns `expr1` if `expr1` evaluates to TRUE, and `expr3` otherwise. `?:` is often referred to as Elvis operator.

This behaves like the Null Coalescing operator `??`, except that `??` requires the left operand to be exactly `null` while `?:` tries to resolve the left operand into a boolean and check if it resolves to boolean `false`.

Example:

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.