# Operators

In this part of the PHP programming tutorial, we talk about PHP operators.

An *operator* is a special symbol which indicates a certain
process is carried out. Operators in programming languages are taken
from mathematics. Programmers work with data. The operators are used to
process the data.

We have several types of operators:

- Arithmetic operators
- Boolean operators
- Relational operators
- Bitwise operators

An operator may have one or two operands. An *operand* is one of
the inputs (arguments) of an operator. Those operators that work with only
one operand are called *unary operators*.
Those who work with two operands are called binary operators.

The + and - signs can be addition and subtraction operators as well as unary sign operators. It depends on the situation.

php > print +2; 2 php > print -2; -2 php > print 2; 2 php > print 2+2; 4 php > print 2-2; 0

The plus sign can be used to indicate that we have a positive number, but it is mostly not used. The minus sign changes the sign of a value.

php > $a = 1; php > print -$a; -1 php > print -(-$a); 1

Multiplication and addition operators are examples of binary operators. They are used with two operands.

php > print 3 * 3; 9 php > print 3 + 3; 6

## The assignment operator

The assignment operator `=`

assigns a value to a variable.
A `variable`

is a placeholder for a value. In PHP, a variable begins
with a `$`

character. (In mathematics, the `=`

operator has
a different meaning. In an equation, the `=`

operator is an equality
operator. The left side of the equation is equal to the right one.)

php > $x = 1; php > print $x; 1

Here we assign a number to an `$x`

variable.

php > $x = $x + 1; php > print $x; 2

The previous expression does not make sense in mathematics, but it is
legal in programming. The expression means that we add 1 to the
`$x`

variable. The right side is equal to 2 and 2 is
assigned to `$x`

.

php > 3 = $x; Parse error: syntax error, unexpected '=' in php shell code on line 1

This code example results in syntax error. We cannot assign a value to a literal.

## Arithmetic operators

The following is a table of arithmetic operators in PHP.

Symbol | Name |
---|---|

`+` | Addition |

`-` | Subtraction |

`*` | Multiplication |

`/` | Division |

`%` | Modulo |

The following example shows arithmetic operations.

<?php $a = 10; $b = 11; $c = 12; $add = $a + $b + $c; $sub = $c - $a; $mult = $a * $b; $div = $c / 3; echo "$add $sub $mult $div\n"; ?>

All these are known operators from mathematics.

$ php arithmetic.php 33 2 110 4

The `%`

operator is called the modulo operator. It finds the remainder
of division of one number by another.

php > print 9 % 4; 1

`9 % 4`

, 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1.

## Primes

A prime number is an integer number greater than 1, which can be divided evenly only by 1 or itself.

<?php $nums = range(0, 100, 1); foreach ($nums as $n) { if ($n <= 1) continue; if ($n == 2 or $n == 3) { echo "$n "; continue; } $i = (int) sqrt($n); $isPrime = true; while ($i > 1) { if ($n % $i == 0) { $isPrime = False; } $i--; } if ($isPrime == True) { echo "$n "; } } echo "\n"; ?>

The modulo operator is used to calculate prime numbers. The algorithm to calculate primes is this: we pick up a number and divide it by numbers, from 1 up to the picked up number. It has been proven that we do not need to try all smaller numbers; it is sufficient to try numbers up to the square root of the chosen number.

$nums = range(0, 100, 1);

We use the `range()`

function to create an array
of integers from 0 to 100.

if ($n <= 1) continue;

By definition, a prime is a number greater than 1; therefore, we skip the calculation and continue with the next number.

if ($n == 2 or $n == 3) { echo "$n "; continue; }

Numbers 2 and 3 are primes.

$i = (int) sqrt($n);

We are OK if we only try numbers smaller than the square root of a number.

while ($i > 1) { ... }

A while loop is used. The `$i`

is the calculated square root of the number.
We use the decrement operator to decrease the `$i`

by one each loop cycle.
When the `$i`

is smaller than 1, we terminate the loop. For example, we have
number 9. The square root of 9 is 3. We will divide 9 by 3 and 2.

if ($n % $i == 0) { $isPrime = False; }

This is the core of the algorithm. If the remainder division operator returns 0 for
any of the `$i`

values then the number in question is not a prime.

$ php primes.php 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

These are the primes between 0 and 100.

## Concatenating strings

We use the dot `.`

operator to concatenate strings.

php > print 'return' . 'of' . 'the' . 'king'; returnoftheking

The dot operator makes one string from four pieces of strings.

php > print 3 . 'apples'; 3apples

We can concatenate strings with numbers with the dot operator. Internally, the number is converted to a string a the two strings are concatenated in the end.

php > print 'apples' * 3; 0 php > print 'apples' - 'oranges'; 0 php > print 'apples' + 'oranges'; 0

Using other operators with strings does not make much sense; we get zero.

php > print (Integer) 'apple'; 0

This is because in a numerical context, a string is equal to zero.

## Boolean operators

In PHP, we have `and`

, `or`

and negation `!`

boolean operators.
With boolean operators we perform logical operations. These are often
used with if and while keywords.

<?php $a = (True and True); $b = (True and False); $c = (False and True); $d = (False and False); var_dump($a, $b, $c, $d); ?>

This example shows the logical `and`

operator. The logical and operator
evaluates to True only if both operands are True.

$ php andop.php bool(true) bool(false) bool(false) bool(false)

The logical `or`

operator evaluates to True if either of the operands is True.

<?php $a = (True or True); $b = (True or False); $c = (False or True); $d = (False or False); var_dump($a, $b, $c, $d); ?>

If one of the sides of the operator is True, the outcome of the operation is True.

$ php orop.php bool(true) bool(true) bool(true) bool(false)

The *negation* operator `!`

makes True False and False True.

<?php $a = ! False; $b = ! True; $c = ! (4<3); var_dump($a, $b, $c); ?>

The example shows the negation operator in action.

$ php negation.php bool(true) bool(false) bool(true)

And, or operators are short circuit evaluated.
*Short circuit evaluation* means that the second argument is only evaluated
if the first argument does not suffice to determine the value of the expression: when the
first argument of and evaluates to false, the overall value must be false; and when the
first argument of or evaluates to true, the overall value must be true.

A typical example follows.

<?php $x = 10; $y = 0; if ($y != 0 and x/y < 100) { echo "a small value"; } ?>

The first part of the expression evaluates to False. The second part of the expression is not evaluated. Otherwise, we would get a Division by zero error.

## Relational Operators

Relational operators are used to compare values. These operators always result in boolean value.

Symbol | Meaning |
---|---|

`<` | strictly less than |

`<=` | less than or equal to |

`>` | greater than |

`>=` | greater than or equal to |

`==` | equal to |

`!=` or `<>` | not equal to |

`===` | identical |

`!==` | not identical |

The table presents eight PHP relational operators.

php > var_dump(3 < 4); bool(true) php > var_dump(3 == 4); bool(false) php > var_dump(4 >= 3); bool(true)

As we already mentioned, the relational operators return boolean values.

Notice that the relational operators are not limited to numbers. We can use them for other objects as well. Although they might not always be meaningful.

php > var_dump("six" == "six"); bool(true) php > var_dump("a" > 6); bool(false) php > var_dump('a' < 'b'); bool(true)

We can compare string objects too. We can use relational operators for different object types. In our case we compare a string with a number.

php > var_dump('a' < 'b');

What exactly happens here? Computers do not know characters or strings. For them, everything is just a number. Characters are special numbers stored in specific tables, like ASCII. So in the end, two ASCII numbers are compared; since a is before b, it has a lower number and so the operation returns true.

<?php echo 'a' < 'b'; echo "\n"; echo 'a is:', ord('a'); echo "\n"; echo 'b is:', ord('b'); echo "\n"; ?>

Internally, the a and b characters are numbers. So when we compare two characters,
we compare their stored numbers. The built-in `ord()`

function returns
the ASCII value of a single character.

$ php compare.php 1 a is:97 b is:98

In fact, we compare two numbers: 97 with 98.

php > print "ab" > "aa"; 1

Say we have a string with more characters. If the first characters are equal, the next ones are compared. In our case, the b character at the second position has a greater value than the a character. That is why "ab" string is greater than "aa" string. Comparing strings in such a way does not make much sense, of course. But it is technically possible.

## Assignment, equality, and identity

As you might notice, there is one sign operator `=`

, two signs
operator `==`

and three signs `===`

operator.
Now we will talk about the differences between these operators.

The one sign `=`

operator is the assignment operator. It loads
a value to a variable.

php > $a = 6; php > echo $a; 6

In the example, we assign a value 6 to the `$a`

variable. The
`$a`

variable now contains number six. We can show
the contents of the `$a`

variable by using the `echo`

command.

The two signs `==`

operator is the loose equality operator. It
is used to test if the values in question are equal. Note that PHP interpreter
does some implicit casting when this operator is used. This leads to some
non-intuitive results.

php > var_dump(false == 0); bool(true) php > var_dump(false == array()); bool(true) php > var_dump(true == 1); bool(true) php > var_dump(true == "string"); bool(true) php > var_dump(117 == "000117"); bool(true)

For many programmers, beginners or programmers coming from other languages, these results might be surprising. If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison is performed numerically.

The three sign `===`

operator is the strict comparison operator.
It is called the *identity operator*. This operator returns true only if the
values of the operands are equal and are of the same type.

php > var_dump(false === 0); bool(false) php > var_dump(false === array()); bool(false) php > var_dump(true === 1); bool(false) php > var_dump(true === "string"); bool(false) php > var_dump(117 === "000117"); bool(false)

As we can see, the identity operator returns the opposite results. This operator is more intuitive and more safe to use.

## Bitwise operators

Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal or hexadecimal symbols are only notations of a number. Bitwise operators work with bits of a binary number. We also have binary logical operators and shift operators.

Bitwise operators are seldom used in higher level languages like PHP.

Symbol | Meaning |
---|---|

`~` | bitwise negation |

`^` | bitwise exclusive or |

`&` | bitwise and |

`|` | bitwise or |

`<<` | left shift |

`>>` | right shift |

The *bitwise negation operator* changes each 1 to 0 and 0 to 1.

php > print ~7; -8 php > print ~-8; 7

The operator reverts all bits of a number 7. One of the bits also determines whether the number is negative. If we negate all the bits one more time, we get number 7 again.

The *bitwise and operator* performs bit-by-bit comparison between
two numbers. The result for a bit position is 1 only if both corresponding bits
in the operands are 1.

00110 & 00011 = 00010

The first number is a binary notation of 6, the second is 3 and the result is 2.

php > print 6 & 3; 2 php > print 3 & 6; 2

The *bitwise or operator* performs bit-by-bit comparison
between two numbers. The result for a bit position is 1 if either of
the corresponding bits in the operands is 1.

00110 | 00011 = 00111

The result is `00110`

or decimal 7.

php > print 6 | 3; 7

The *bitwise exclusive or operator* performs bit-by-bit comparison
between two nubmers. The result for a bit position is 1 if one or the
other (but not both) of the corresponding bits in the operands is 1.

00110 ^ 00011 = 00101

The result is `00101`

or decimal 5.

php > print 6 ^ 3; 5

Finally, we also have bitwise shift operators. The
*bitwise shift operators* shift bits to the right or left.

number << n : multiply number 2 to the nth power number >> n : divide number by 2 to the nth power

These operators are also called arithmetic shift.

00110 >> 00001 = 00011

We shift each of the bits of number six to the right. It is equal
to dividing the six by 2. The result is `00011`

or decimal 3.

php > print 6 >> 1; 3

00110 << 00001 = 01100

We shift each of the bits of number six to the left. It is equal
to multiplying the number six by 2.
The result is `01100`

or decimal 12.

php > print 6 << 1; 12

## Compound assignment operators

The compound assignment operators consist of two operators. They are shorthand operators.

php > $i = 1; php > $i = $i + 1; php > print $i; 2 php > $i += 1; php > print $i; 3

The `+=`

compound operator is one of these shorthand operators.
They are less readable than the full expressions but experienced programmers
often use them.

Other compound operators are:

-= *= .= /= %= &= |= ^= >>= <<=

## Operator precedence

The *operator precedence* tells us which operators are
evaluated first. The precedence level is necessary to avoid
ambiguity in expressions.

What is the outcome of the following expression, 28 or 40?

3 + 5 * 5

Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.

(3 + 5) * 5

To change the order of evaluation, we can use square brackets. Expressions inside square brackets are always evaluated first.

The following list shows common PHP operators ordered by precedence (highest precedence first):

Operator(s) | Description |
---|---|

`++ --` |
increment/decrement |

`(int) (float) (string) (array) (object) (bool)` |
casting |

`!` |
logical "not" |

`* / %` |
arithmetic |

`+ - .` |
arithmetic and string |

`<< >>` |
bitwise |

`< <= > >= <>` |
comparison |

`== != === !==` |
comparison |

`&&` |
logical "and" |

`||` |
logical "or" |

`? :` |
ternary operator |

`= += -= *= /= .= %=` |
assignment |

`and` |
logical "and" |

`xor` |
logical "xor" |

`or` |
logical "or" |

`,` |
comma operator |

Operators on the same line in the list have the same precedence.

<?php print 3 + 5 * 5; print "\n"; print (3 + 5) * 5; print "\n"; var_dump(! True or True); var_dump(! (True or True)); ?>

In this code example, we show some common expressions. The outcome of each expression is dependent on the precedence level.

var_dump(! True or True);

In this case, the negation operator has a higher precedence. First, the first True value is negated to False, then the or operator combines False and True, which gives True in the end.

$ php precedence.php 28 40 bool(true) bool(false)

The relational operators have a higher precedence than logical operators.

<?php $a = 1; $b = 2; if ($a > 0 and $b > 0) { echo "\$a and \$b are positive integers\n"; } ?>

The and operator awaits two boolean values. If one of the operands would not be a boolean value, we would get a syntax error.

$ php positive.php $a and $b are positive integers

## Associativity

Sometimes the precedence is not satisfactory to determine the outcome
of an expression. There is another rule called
*associativity*. The associativity of operators determines the
order of evaluation of operators with the *same*
precedence level.

9 / 3 * 3

What is the outcome of this expression, 9 or 1? The multiplication, deletion,
and the modulo operator are left to right associated. So the expression is evaluated
this way: `(9 / 3) * 3`

and the result is 9.

Arithmetic, boolean, relational, and bitwise operators are all left to right associated.

On the other hand, the assignment operator is right associated.

php > $a = $b = $c = $d = 0; php > echo $a, $b, $c, $d; 0000

If the association was left to right, the previous expression would not be possible.

The compound assignment operators are right to left associated.

php > $j = 0; php > $j *= 3 + 1; php > print $j; 0

You might expect the result to be 1. But the actual result is 0, because of the associativity. The expression on the right is evaluated first and than the compound assignment operator is applied.

## Other operators

PHP has a *silence ( @ ) operator*. It is used to turn off
error messaging. It is typically used with
network or database connections. This operator should be used
with caution, because it can lead to
debugging issues.

php > echo 3 / 0; Warning: Division by zero in php shell code on line 1 php > echo @ (3 / 0); php >

In the first case, we receive a division by zero error message. In the
second case, the `@`

operator turns off the error message.

The *reference ( & ) operator*. It creates a reference to an object.

php > $a = 12; php > $b = &$a; php > echo $b; 12 php > $b = 24; php > echo $b; 24 php > echo $a; 24

In the above example, we pass a value to `$a`

variable and pass a
reference to the `$a`

to the `$b`

variable.

php > $b = &$a;

We create a new variable `$b`

pointing to the `$a`

variable.
In other words, we create an alias for the `$a`

variable.

php > $b = 24; php > echo $b; 24 php > echo $a; 24

Assigning a new value to `$b`

will also affect the `$a`

.

The *backtick ( ` ) operator* is used to execute commands. It is
identical to the `shell_exec()`

function call.

php > $list = `ls -l | head -3`; php > echo $list; total 52 -rw-rw-r-- 1 janbodnar janbodnar 130 Jan 19 11:35 andop.php -rw-rw-r-- 1 janbodnar janbodnar 140 Jan 19 11:21 arithmetic.php

We execute an `ls`

command, which on Unix systems lists the contents of the
current directory.

In this part of the PHP tutorial, we covered the PHP operators.