PHP Operations

Chapter 9 29 mins

Learning outcomes:

  1. What are operations, operators and operands
  2. Arithmetic operations
  3. Relational operations
  4. Assignment operations
  5. Logical operations
  6. Increment/decrement operations
  7. String operations

What are operations?

In the world of programming, there are tons and tons of operations some of which can be performed on numbers, some on strings, some on Booleans, some on any arbitrary value, and so on.

But what exactly is an operation?

An operation is a process or function that takes place on given values.

A very simple example of an operation is that of addition. Addition, as we all know, is to sum up two numbers together.

Now as it turns out, every single operation in a language has to be represented in some way by some symbol or keywrord.

For instance, addition is represented by the symbol +. Similarly, string concatenation is represented by the symbol ., and so on.

Such a symbol or keyword has a special name i.e. an operator.

An operator is a symbol or keyword that represents a given operation.

Certain operators require two values to operate such as the arithmetic operators (addition, subtraction, etc.), concatenation, etc. These operators are known as binary operators, where the term 'binary' represents 'two'.

Then there are operators than only require one value. These are known as unary operators. Examples include post-increment ++ as in $i++.

There is even a ternary operator in PHP, more generally called as the conditional operator. We'll explore it in the PHP Control Flow unit.

The values required to be put around an operator, on which the underlying operation is performed, are known as operands.

An operand is the value on which an operation happens.

For instance, in the expression 2 + 5, 2 and 5 are the operands, + is the operator, and the operation being performed is addition.

With this distinction in mind as to what is an operation, an operator and an operand, it's time to finally see all the different kinds of operators in PHP.

Arithmetic operations

Nearly all programming languages allows the programmer to perform the elementary arithmetic operations on numbers. PHP is no way behind.

We've seen all the basic arithmetic operations in the previous chapters. The likes of addition, subtraction, multiplication, division, exponentiation and modulo.

Here's a quick recap:

OperationOperatorExamplePurpose
Addition+$x + $yAdds the given numbers.
Subtraction-$x - $ySubtracts the second number from the first one.
Multiplication*$x * $yMultiplies the given numbers.
Division/$x / $yDivides the first number with the second number.
Exponentiation**$x ** $yRaises the first number to the power of the second number
Division/$x % $yComputes the remainder in $x / $y.

The snippet below demonstrates all these operations:

<?php

$x = 2;
$y = 10;

echo 'Addition: ', $x + $y, "\n";
echo 'Subtraction: ', $x - $y, "\n";
echo 'Multiplication: ', $x * $y, "\n";
echo 'Division: ', $x / $y, "\n";
echo 'Exponentiation: ', $x ** $y, "\n";
echo 'Modulo: ', $x % $y, "\n";
Addition: 12 Subtraction: -8 Multiplication: 20 Division: 0.2 Exponentiation: 1024 Modulo: 2

Simple.

Relational operations

When working with control flow structures in PHP, it's extremely common to compare different values to one another. For instance, before printing 'Even', we'd have to check if an integer is even. This is done using the === and the % operators.

Relational operators are what enable us to compare two values to one another. The word 'relational' comes from the fact that the operator describes a relation between the given operands, for example, whether they are equal to one another or not.

Sometimes relational operators are also referred to as comparison operators in PHP.

Below shown is a list of the most common relational operators in PHP:

OperationOperatorExamplePurpose
Identity===$x === $yReturns true if $x is identical in value to $y, or else false.
Non-identity!==$x !== $yReturns false if $x is identical in value to $y, or else true.
Equality==$x == $yReturns true if $x is equal in value to $y after type juggling, or else false.
Non-equality!=, <>$x != $y, $x <> $yReturns false if $x is equal in value to $y after type juggling, or else true.
Less than<$x < $yReturns true if $x is less than $y, or else false.
Less than or equal to<=$x <= $yReturns true if $x is less than or equal to $y, or else false.
Greater than>$x > $yReturns true if $x is greater than $y, or else false.
Greater than or equal to>=$x >= $yReturns true if $x is greater than or equal to $y, or else false.

Let's try to put all of these operations into real examples.

Suppose we want to print 'Even' if a given integer $a is even or else print 'Odd'. This can be accomplished as follows:

<?php

$a = 10;

if ($a % 2 === 0) {
   echo 'Even';
}
else {
   echo 'Odd';
}
Even

First we check $a for an even parity and then fallback with the case that it's odd.

Try changing $a from 10 to any odd integer in the code above and then rerun it.

This same idea can also be accomplished using the non-identity operator (!==) by switching the conditional cases, as follows:

<?php

$a = 10;

if ($a % 2 !== 0) {
   echo 'Odd';
}
else {
   echo 'Even';
}
Even

Here, first we check $a for an odd parity and then fallback with the case that it's even.

Let's consider another example.

Suppose we want to print 'Above 18' if a given variable $age is greater than 18, or else print 'Not above 18'. This is done below using the greater-than (>) operator:

<?php

$age = 18;

if ($age > 18) {
   echo 'Above 18';
}
else {
   echo 'Not above 18';
}
Not above 18

As before, the same idea can be accomplished by reversing the conditional cases and using the less-than or equal to (<=) operator:

<?php

$age = 18;

if ($age <= 18) {
   echo 'Not above 18';
}
else {
   echo 'Above 18';
}
Not above 18

First we check if $a is less than or equal to 18 and print 'Not above 18' if it is. Else, we assume that $age is greater than 18 and likewise print 'Above 18'

One thing that we're not doing above is that we're not checking if the value stored in $age is really an integer.

For instance, in the last code snippet above, if $age is not an integer, the else block is executed ultimately printing 'Above 18'.

This problem can be rectified very easily, thanks to the is_int() function we learned about before.

Consider the code below:

<?php

$age = 'random';

if (is_int($age) === false) {
   echo 'Invalid value';
}
elseif ($age <= 18) {
   echo 'Not above 18';
}
else {
   echo 'Above 18';
}
Invalid value
The condition is_int($age) === false can be more neatly expressed as !is_int($age) where ! is the logical NOT operator. We'll explore ! later on in this chapter.

Sparingly use == and != (or <>)

One important thing to note in PHP's relational operators are == and != (or <>). They are the equality and non-equality operators, respectively, and are slightly different than the identity (===) and non-identity (!==) operators.

The reason we didn't use them in any example is because they perform a lot of type juggling behind the scenes.

Type juggling is simply to play around with the type of a datum and convert it from one form to another, and then to another, in order to perform a good comparison with another datum.

Using == can lead to multiple implicit checks while running a piece of code and sometimes even undefined behavior.

Instead, using === is considered a good practice. It makes sure that what is written is exactly what happens and not any unknown implicit type conversions behind the scenes.

Even JavaScript has this idea of loose equality comparisons done by the same operators == and !=. And akin to PHP, JavaScript developers don't really recommend their usage.

Assignment operations

Needless to say, assignment is by far one of the most common and useful operations in any programming language. There are tons and tons of variables created in all but the simplest programs.

Typically, the = symbol is used as the assignment operator in most languages and that's exactly the case with PHP.

Consider the code below:

<?php

$i = 0;

We create a variable $i and assign it the value 0.

Note that the left-hand side of an assignment operation can only host a variable (or any identifier where something can be stored). It's illegal to put any arbitrary expression there.

For example, in the code below, we write 10 on the left-hand side of = and consequently get a syntax error.

<?php

10 = 0;
Parse error: syntax error, unexpected token "=" in <path> on line 3

So far is this course we've been treating assignment as a standalone statement. However, since it's an operation, assignment is merely an expression. And we know that all expressions resolve down to a value, right?

Similarly, the assignment operation evaluates down to the value assigned to the variable (or identifier).

This can be seen below:

<?php

echo $i = 0;

We echo the expression $i = 0 directly instead of first defining it on a separate line and then printing it. Regardless, since it's an expression that, in this case, resolves down to 0, 0 is ultimately printed.

0

Moreover, following from the fact that assignment resolves down to the value assigned, we can define and assign multiple variables in one go instead of putting each assignment on a separate line.

Consider the code below:

<?php

$a = 0;
$b = 0;
$x = 0;
$y = 0;

Here we are trying to define four variables $a, $b, $x and $y, each set to 0. The code isn't obviously wrong, but a little bit too long.

Using the power of assignment, we can easily express this same notion as follows:

<?php

$a = $b = $x = $y = 0;

The way this works is very simple. Once the engine is done parsing the source code, it begins evaluating each = starting from the right-hand side. That is, first $y = 0 is evaluated. This defines $y, sets it to 0, and returns 0.

Next up, $x = 0 is evaluated (where the 0 is the result of the first evaluation) and the same process repeats. This goes on until 0 is assigned to $a at which point the whole statement completes.

Apart from the mere assignment operator, PHP provides multiple assignment operators that do more than just assignment. These operators perform a certain operation on the given operands and then assign a value to one of them.

The table below shows some of these:

OperationOperatorExampleSame as
Addition assignment+=$x += $y$x = $x + $y
Subtraction assignment-=$x -= $y$x = $x - $y
Multiplication assignment*=$x *= $y$x = $x * $y
Division assignment/=$x /= $y$x = $x / $y
Exponentiation assignment**=$x **= $y$x = $x ** $y
Modulo assignment%=$x %= $y$x = $x % $y
Concatenation assignment.=$x .= $y$x = $x . $y
Bitwise OR assignment|=$x |= $y$x = $x | $y

Let's take the addition-assignment (+=) operator. Consider the code below:

<?php

$a = 10;
$b = 60;

echo $a += $b;
70

The expression $a += $b first adds $a and $b together, then assigns the result to $a, and then finally returns the result. Thus, 70 is printed.

You might be thinking that this is redundant and that we could easily do something $i = $i + 10 instead of $i ++ 10. In other words, you might be thinking that there isn't really a big deal to these special assignment operators.

Well, these special operators only start to show their advantage once we try to operate and assign to an identifier that's very long when written.

For instance, as we'll see later in the OOP unit, it's common to refer to properties of a given object one after another to reach a given property and then assign to it meanwhile performing an operation:

Consider the code below:

<?php

/* ... */

// Increase the vote count by 10.
$user_store->question(1)->votes = $user_store->question(1)->votes + 10;
We'll explore the -> operator in the PHP OOP unit.

Here we try to add 10 to the given identifier $user_store->question(1)->votes and assign the result back to it. As can be seen, the expression has become quite long due to the repetition of the identifier.

A much better approach would be to use the += operator instead. This is what we do below:

<?php

/* ... */

// Increase the vote count by 10.
$user_store->question(1)->votes += 10;

Short and concise.

Logical operations

Combining Booleans together is a routine activity in conditional programming. The world of electronics and computing has much to say to Boolean operations, also known as logical operations.

They come directly from the beautiful mathematical theory of propositions and propositional operators.

To learn more about propositions and propositional operators, take our course on Elementary Logic.

So what are logical operation?

A logical operation is a way to create a new Boolean based on the value of an existing Boolean.

The three most common logical operations in PHP and most languages are logical NOT, OR, and AND. The table below summarizes them along with their respective operators.

OperationOperatorExamplePurpose
Logical NOT!!$xInverts the Boolean value of $x.
Logical OR||$x || $yReturns true if either of $x or $y are true, or else false.
Logical AND&&$x && $yReturns true if both $x and $y are true, or else false.

Let's consider some examples.

Recall from the previous discussion an if statement set up with the condition is_int($age) === false:

<?php

$age = 'random';

if (is_int($age) === false) {
   echo 'Invalid value';
}
elseif ($age <= 18) {
   echo 'Not above 18';
}
else {
   echo 'Above 18';
}

Clearly, we can see that we mean to execute a piece of code in the if statement if $age is not an integer i.e. is_int($age) returns false.

A better approach would be use the logical NOT operator in this case.

The logical NOT operator, denoted as !, simply inverts the value of the operand following it.

The following table summarizes the semantics of !:

$x!$x
truefalse
falsetrue

Taking this idea to our previous example, we want to print 'Invalid value' if $age is not an integer. Hence, we need to check for the condition !is_int($age). If this expression evaluates to true, that simpy means that is_int() returned false.

<?php

$age = 'random';

if (!is_int($age)) {
   echo 'Invalid value';
}
elseif ($age <= 18) {
   echo 'Not above 18';
}
else {
   echo 'Above 18';
}
Invalid value

Simple.

An easy way to remember how to use ! in a condition is to write out the condition in English and then translate it back to code. For instance, going with the previous example, we'd write the whole if statement as 'if $age is not an integer, then do this.'

When translating back to code, 'not' becomes ! whereas 'an integer' becomes is_int($age).

As we'll see in the following chapters in this course, ! is not something used occasionally — it's an extremely common and useful operator.

Moving on, often times it's desirable to combine multiple conditions with one another. That's where the logical OR and the logical AND operators come into the game.

The logical OR operator, denoted as ||, evaluates to true is either of its operands evaluates to true, or else evaluates to false.

Here's a table summarizing the semantics of ||:

$x$y$x || $y
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

Let's consider an example:

Suppose we want to print 'Divisible by 2 or 3' if an integer $x is divisible by 2 or by 3, or by both.

In the typical if style, we'd implement this as follows:

<?php

$x = 20;

if ($x % 2 === 0) {
   echo 'Divisible by 2 or 3';
}
elseif ($x % 3 === 0) {
   echo 'Divisible by 2 or 3';
}
Divisible by 2 or 3

We have an if statement to check for divisibility by 2 and then an elseif statement to check for divisibility by 3. In either case, we print the same thing.

Now using the power of ||, we can shorten this code and make it much more readable:

<?php

$x = 20;

if ($x % 2 === 0 || $x % 3 === 0) {
   echo 'Divisible by 2 or 3';
}
Divisible by 2 or 3

The || operator, as used here, simply evaluates to true if either $x % 2 === 0 or $x % 3 === 0 is met. Otherwise, it evaluates to false.

Time to move on to the logical AND operator.

The logical AND operator, denoted as &&, evaluates to true if both the given operands evaluate to true, or else evaluates to false.

The table below summarizes its semantics:

$x$y$x && $y
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

As before, let's consider an example.

Suppose we want to print 'Divisible by 2 and 3' if a given integer $x is divisible by both 2 and 3. In the typical if style, this would be done as follows:

<?php

$x = 6;

if ($x % 2 === 0) {
   if ($x % 3 === 0) {
      echo 'Divisible by 2 and 3';
   }
}
Divisible by 2 and 3

We have an if statement checking for divisbility by 2 and then an if statement nested inside it checking for divisbility by 3.

Once again, this could more succinctly be written using && as follows:

<?php

$x = 6;

if ($x % 2 === 0 && $x % 3 === 0) {
   echo 'Divisible by 2 and 3';
}
Divisible by 2 and 3

Simple.

Note that these aren't the only logical operators provided by PHP. There are a couple more such as and, or and xor. We'll cover all of them in the PHP Control Flow unit.

Increment and decrement operations

As we've seen in the PHP Control Flow chapter, PHP provides a shortcut to increment and decrement a variable's value. That's using the ++ and -- operators.

Now there are two kinds of increment/decrement operators as demonstrated below:

OperationOperatorExamplePurpose
Prefix increment++++$xIncrement $x by 1 and then return the result.
Postfix increment++$x++Return $x and then increment it by 1.
Prefix decrement----$xDecrement $x by 1 and then return the result.
Postfix decrement--$x--Return $x and then decrement it by 1.

The example below demonstrates the two increment (++) operators:

<?php

$x = 0;

echo '$x: ', $x, "\n";
echo '++$x: ', ++$x, "\n";
echo '$x++: ', $x++, "\n";
echo '$x: ', $x, "\n";
$x: 0 ++$x: 1 $x++: 1 $x: 2

Since ++ is merely a kind of assignment, it's invalid to use it on a literal value. This can be seen as follows:

<?php

10++;
Parse error: syntax error, unexpected token "++" in <path> on line 3

Increment operators are most commonly used with counter variables i.e. variables meant to keep track of indexes in a sequence, or other counting enumerations.

A familiar example for the increment operator is that of the for loop as shown below:

<?php

$nums = [1, 2, 10, -5];

for ($i = 0; $i < count($nums); $i++) {
   echo $nums[$i], "\n";
}
1 2 10 -5

Here in the third expression of the for loop's header, we use $i++. This is to increment $i after the given iteration so as to proceed closer and closer to the termination condition of the loop.

Note that it would be completely fine even if we use the prefix increment (++$x) operator here:

<?php

$nums = [1, 2, 10, -5];

for ($i = 0; $i < count($nums); ++$i) {
   echo $nums[$i], "\n";
}
1 2 10 -5

String operations

When we talk about strings, we can't end the conversation without talking about the idea of concatenation.

To recap it, concatenation is the joining of two strings into one single string. In PHP, concatenation is done using the . operator.

OperationOperatorExamplePurpose
Concatenation.$x . $yJoins the strings $x and $y together and returns the result.

Below shown is an example:

<?php

$end = '!';
echo 'Hello ' . 'World' . $end;
Hello World!

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage