Using Operators in PHP

using-operators-in-php

Operators are the secret sauce to your PHP. In fact they are the secret sauce to all programming because without them, you’d be doing a whole lot of nothing with the data you are trying to manipulate or operate on!

Operators are used with arguments. They are the data being operated on, also called Operands. One or many arguments can be used in these operations, though most commonly you will see two arguments. For example 10 > 5 or $foo = $bar.

Arithmetic Operators

If you remember or know Algebra then arithmetic operators are going to be easy peasy for you as they are just the normal mathematical operators.

Check em out:

Operator Name Example
+ Addition
Subtraction
* Multiplication
/ Division
% Modulus

By using these operators in conjunction with the assignment operator, you can store results like so:
$sum = $x + $y;

What this does is take the value of $x and $y then stores it in the variable $sum.

Subtraction would work in a similar fashion. Put calculations on the right of the = and store the value to the left of the =.

You would read it as “$sum is set to $x + $y”.

One thing to note about the subtraction operator is that it can also be used to denote a negative value stored in a variable like so:
$a = -1;

Multiplication and division

In programming you use the asterisk * for multiplication and the forward slash / for division.

A special case arithmetic operator is the modulus which calculates the remainder of two divided numbers. For example:

The value stored in the $result variable is the remainder when you divide 29 by 10 which comes out to 9.

The arithmetic operators usually deal with integer and double data types. Due to the loosely typed nature of the language, applying these operators to strings will cause unexpected results as PHP starts automagically converting strings to numbers. Pay close attention to your types in order to avoid creating bugs.

Operating on Strings

The concatenation operator or dot . is that magical glue that allows you to stick strings together. It’s really fun and I know you will love it. An example is in order:

The result is “I am awesome” and yes ladies and gentlemen, you are awesome.

Assignment Operators

To equals or not to equals, that is the question. The handy dandy = sign does not mean ‘equals to’ rather it means ‘is set to’. In a sense you might start to read code from right to left. When you see

You could read it in a right to left fashion as in, “cool text is assigned to $myvalue” or left to right such as “$myvalue is set to cool text”. Whatever makes sense to you!

Values Returned from Assignment

The assignment operator returns a value just like other operators. For example:

$one + $two

Is an expression that results in the value of adding $one and $two.

Another example might be:

$ten = 10;

The value of this whole expression is integer ten.
Using this technique, you can create more involved expressions like:

$foo = 16 + ($bar = 5);

This line sets the value of the $foo variable to 21. First we evaluate the code between the parentheses setting 5 to $bar, then adding 16 to 5, and finally assigning that entire value to $foo. As you can see the parentheses work the same way as they do in math, which is to give precedence to the sub expression between the parentheses.

Combination Operators

Many times in programming you will need to add a value to a variable such as

$x = $x + 10;

Rather than write it out in long form, you can use a combination operator like

$x += 10;

Combined assignment operators exist for all of the arithmetic operators and for the
string concatenation operator.

Pre and Post Increment and Decrement

Pre and post increment (++) and decrement (–) operators share traits with the +=
and -= operators, with some important differences.

Increment operators do two things, which is to increment and assign a value.

On line two, the pre-increment operator is invoked. Interestingly, $hi will get 1 added to it’s value and then echoed out to the screen as 8. Had the ++ come after the variable, it would be printed to the screen as 7, and then it’s value would be incremented in memory.

The Reference Operator

The reference operator is represented by an &. What this does is to make reference to the memory address of a variable rather than make a copy of the value itself. Typically what happens when you create a variable and then assign that variable to a different one, a copy gets created.

So setting $x = 7, $y = $x , and $x = 15 would leave you with 7 stored in $y and 15 stored in $x.

Conversely if you did $x = 7, $y = &$x , and $x = 15 both $x and $y would have value 15. This happens because $x and $y now point to the same memory address. To change this relationship, you can use the unset() function.

Comparison Operators

When you need to check the logical value of an expression to true or false, you would use one of the many comparison operators.

The Equal Operator

It’s easy to get the = and the == operators mixed up. The first refers to assignment, the second refers to equality. Using == allows you to check if two values are equal to one another. True is returned if they are equal and false is returned if they are not. Typically non zero values are true and zero values are false.

Consider:

$five = $two now evaluates to true! This is because the value 2 gets assigned to $five, and 2 is a non zero value.

On the other hand:

$five == $two will now evaluate to false. Pay attention to your operators!

Other Comparison Operators

There are many other comparison operators that you will need to be aware of, they are summarized here:

==

Equals

$c == $f
===

Identical

$c === $f
!=

Not equal

$c != $f
!==

Not identical

$c !== $f
<>

Not equal (comparison operator)

$c <> $f
< Less than

$c < $f
>

Greater than (comparison operator)

$c > $f
<= Less than or equal to

$c <= $f
>=

Greater than or equal to

$c >= $f

Logical Operators

Logical operators are important to test conditions. You can use AND, OR, XOR, and NOT for this purpose. These are often used for checking conditions in control flow structures and loops.

! NOT !$f Returns true if $f is false and vice versa
&& AND $c && $f Returns true if both $c and $f are true; otherwise false
|| OR $c || $f Returns true if either $c or $f or both are true; otherwise false
and AND $c and $f Same as &&, but with lower precedence
or OR $c or $f Same as ||, but with lower precedence
xor XOR $c x or $f Returns true if either $c or $f is true, and false if they are both true or both false.

Bitwise Operators

By using bitwise operators on integers, you will be able to deal with the exact bits that represent the integer in question. Bitwise operators are more often used in a low level fashion such as OS or Network programming in C. They are still available to you in PHP however and we have them listed here:

& Bitwise AND $c & $f Bits set in $c and $f are set in the result.
| Bitwise OR $c | $f Bits set in $c or $f are set in the result.
~ Bitwise NOT ~$c Bits set in $c are not set in the result and vice versa.
^ Bitwise XOR $c ^ $f Bits set in $c or $f but not in both are set in the result.
<< Left shift $c << $f Shifts $c left $f bits.
>> Right shift $c >> $f Shifts $c right $f bits.

But Wait There’s More! (Operators)

Let’s cover the remaining operators you’ll run into now. The comma operator , is an important one as it is used to separate arguments in functions and items in an array.

You will also want to be aware of the new and -> operators in order to create a new object and access methods and properties within said object.

Kind of a control structure but formally listed as an operator is the ternary operator. ?: This handy dandy little bugger is great for having a shorthand form of an if else statement.
The form the ternary operator follows is:

condition ? value if true : value if false

Error Suppression Operator

PHP has many useful errors but sometimes you may not want to see them. In this case you can use the @ operator to suppress them like so:

$error = @(200/0)

Normally this code would through a nasty warning, but we have suppressed it here with @.

Array Operators

Arrays are great fun and very useful. As such, we have numerous operators to use on our arrays to make them easy to work with.

+ Union $c + $f Returns an array containing everything in $c and $f
== Equality $c == $f Returns true if $c and $f have the same key and pairs
=== Identity $c === $f Returns true if $c and $f have the same key and value pairs the same order
!= Inequality $c != $f Returns true if $c and $f are not equal
<> Inequality $c <> $f Returns true if $c and $f are not equal
!== Non Identity $c !== $f Returns true if $c and $f are not identical

Type Operator

In object oriented programming we will cover the instanceof operator. It is used to check if an object is an instance of a certain class. You would use it like so:

If you made it this far, nice work! You now have the skills to operate successfully on your data in PHP.