# PHP Operators

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

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

`$name = $_POST['name'] ?? 'nobody';`

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

`$name = $_GET['name'] ?? $_POST['name'] ?? 'nobody';`

When using coalescing operator on string concatenation don't forget to use parentheses ()

```
$firstName = "John";
$lastName = "Doe";
echo ($firstName ?? "Unknown") . " " . ($lastName ?? "");
```

### Output

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

```
// Integers
print (1 <=> 1); // 0
print (1 <=> 2); // -1
print (2 <=> 1); // 1
// Floats
print (1.5 <=> 1.5); // 0
print (1.5 <=> 2.5); // -1
print (2.5 <=> 1.5); // 1
// Strings
print ("a" <=> "a"); // 0
print ("a" <=> "b"); // -1
print ("b" <=> "a"); // 1
```

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.

`usort($list, function($a, $b) { return $a->weight <=> $b->weight; });`

In PHP 5 this would have required a rather more elaborate expression.

```
usort($list, function($a, $b) {
return $a->weight < $b->weight ? -1 : ($a->weight == $b->weight ? 0 : 1);
});
```

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

```
// List files
$output = `ls`;
echo "<pre>$output</pre>";
```

Note that the execute operator and shell_exec() will give the same result.

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

```
$i = 1;
echo $i;
```

### Output

```
// Pre-increment operator increments $i by one, then returns $i
echo ++$i;
```

### Output

```
// Pre-decrement operator decrements $i by one, then returns $i
echo --$i;
```

### Output

```
// Post-increment operator returns $i, then increments $i by one
echo $i++;
```

### Output

```
// Post-decrement operator returns $i, then decrements $i by one
echo $i--;
```

### Output

### 5. Logical Operators (&&/AND and ||/OR)

In PHP, there are two versions of logical AND and OR operators.

Operator True 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:

Evaluation Result 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.

### 6. String Operators (. and .=)

There are only two string operators:

```
$a = "a";
$b = "b";
$c = $a . $b;
```

### Output

```
$a = "a";
$a .= "b";
```

### Output

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

```
$a = 4;
$b = '4';
if ($a == $b) {
echo 'a and b are equal'; // this will be printed
}
if ($a === $b) {
echo 'a and b are identical'; // this won't be printed
}
```

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 (!==)

### 8. Combined Assignment

The combined assignment operators are a shortcut for an operation on some variable and subsequently assigning this new value to that variable.

**Arithmetic:**

```
$a = 1; // basic assignment
$a += 2; // read as '$a = $a + 2'; $a now is (1 + 2) => 3
$a -= 1; // $a now is (3 - 1) => 2
$a *= 2; // $a now is (2 * 2) => 4
$a /= 2; // $a now is (16 / 2) => 8
$a %= 5; // $a now is (8 % 5) => 3 (modulus or remainder)
// array +
$arrOne = array(1);
$arrTwo = array(2);
$arrOne += $arrTwo;
```

**Processing Multiple Arrays Together**

`$a **= 2; // $a now is (4 ** 2) => 16 (4 raised to the power of 2)`

Combined concatenation and assignment of a string:

```
$a = "a";
$a .= "b"; // $a => "ab"
```

Combined binary bitwise assignment operators:

```
$a = 0b00101010; // $a now is 42
$a &= 0b00001111; // $a now is (00101010 & 00001111) => 00001010 (bitwise and)
$a |= 0b00100010; // $a now is (00001010 | 00100010) => 00101010 (bitwise or)
$a ^= 0b10000010; // $a now is (00101010 ^ 10000010) => 10101000 (bitwise xor)
$a >>= 3; // $a now is (10101000 >> 3) => 00010101 (shift right by 3)
$a <<= 1; // $a now is (00010101 << 1) => 00101010 (shift left by 1)
```

### 9. Basic Assignment (=)

`$a = "some string";`

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!

```
$a = 3;
$b = ($a = 5);
```

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.