PHP operators (part 1)

Coding (Php 7.x)


There are several operators you must learn to become proficient in PHP here is where
 
/img/blog/php-operators.jpg

Introduction

 

 

So, in the previous parts of this series you've seen the basics of PHP,


You have seen what are the basic constructs that this language gives you,

 

You have already seen that there are several types of variables (divided into simple and composite).

 

Now we have finished playing and we start doing things seriously!

 

The question that today's blog post will answer is: 

"Now that I know how to create variables how can I insert them in the flow of my code?".

 

The answer is: through operators,

 

PHP operators allow you to move through the code, to update variables, to lead visitors of your web application to one direction or another (through the use of control structures).

 

There are different types of operators,

 

some that you will use every day many times a day, others that you will rarely use, but once you understand how they work they will make you a web developer much above average if not top 10% among your colleagues.

 

 

PHP Basics for Expert Developers

 

This blog post is part of a series called "PHP Basics for Expert Developers".

 

In this series, you are going to learn the basics of PHP but you will also see many small tips and features that you will only find in books and advanced tutorials.

 

Depending on your level you may simply want to read them sporadically or skip them altogether.

 

You do not have to learn all that is written here by heart!

 

Simply read, find out that certain features or techniques exist and return to these pages when you feel ready for the next level.

PHP basics for expert web developers (1' part)
Construct and Comments of PHP 7
How to use variables (PHP 7)
Composite variable in PHP (Arrays, Object and more)
PHP operators (part 1)
PHP Operators (part 2)
Conditional Structures in PHP
Loops in PHP(Tutorial)

 

 

Also, this blog post is divided into a few main sections

Arithmetic Operators
Logic Operators
Ternary Operator
Null Coalescing Operator
Spaceship Operator
Bitwise Operators
Conclusion

 

 

Operators

 

In PHP there are different types of operators.

 

They range from arithmetic operators to logical operators through assignment operators, reference operators, spaceships and Bitwise.

 

Each of them has its own well-defined purpose that you will see right now.
 

 

 

Arithmetic Operators

 

The arithmetic operators are the same ones that your teacher taught you at the elementary school.

 

They are the additions, subtractions, divisions, multiplications, then you got power indicated by the symbol ** and modulus indicated by the symbol %.

 

 


There are two types of arithmetic operators that take into account two arguments (which are called binary) and operators that take into consideration only one argument (they are called unary).


In turn,

Unary operators are divided into two types: Prefix and Postfix.

 

These types change depending on whether the operator appears before or after the variable you want to be changed.

 

If the operator appears before the variable (Prefix) then the interpreter, the PHP parser will evaluate the operation and the changed variable will return.

 

If instead,

 

the operator appears after the variable (Postfix in this case) then the interpreter will return the variable as if the statement had never been executed and only after performing the operation requested on the variable.
 

 

 

Logic Operators

 

In order to understand what logical operators are, think of them as if they were conjugations in grammar.

 

The purpose of using logical operators in programming languages such as PHP is to perform more complex conditions because it can, in fact, connect different conditions in one.

 

These new conditions make operators more precise and easy to handle.

 

There are seven different types of logical operators in PHP.

 

They are divided into groups of 2.

 

There are two "and", two "or", two "xor" and one "not".

 

They are paired because PHP uses both symbols and words to represent logical operators, thus, in a condition, you can write both the literal word "and" or the && symbol.

 

The same applies to the word "or" or the symbol || and the word "xor" or ^.

 

Logical operators are generally used between two conditions,

 

creating a sort of bigger condition that will be true or false based on the relationship between the logical operator and the two conditions in use.

 

If the operator is "and" or && for the main condition to be true, both conditions must be evaluated as true.

 

In case it is the "or" or || operator between your statement for, the main condition to be evaluated as true one between the first and second condition must be evaluated as true,

 

in the case of "xor" or ^ one of the two conditions must be evaluated as true but not both. 

 

"not" operator is the simplest one and it is indicated by the symbol "!" the condition is simply reversed to the current situation.

 

Unlike the other logical operator the word: "not" cannot be used in a condition, which means the only way you can create a not statement is by prefix the condition with the symbol "!"
 

 

Ternary Operator

 

The use of the ternary operator is rather old. 

 

PHP uses the same format used by C, which is a programming language developed by Dennis Ritchie between 1969 and 1973.

 

It consists of a condition followed by a question mark and then two expressions divided by a colon.

 

If the condition is true then the first expression will be taken into consideration otherwise the expression taken into consideration will be the second one.

 

Look at ternary operators as if they were simple if-else but for a simple operation like assignment or date echo, or at least here is where I find it more useful.

 

Here is an example:
 

echo (isset($var)) ? "the variable is set" : " the variable is not set ";

 

As you can see the syntax in the example would be identical to an if-else statement.

 

Once you've done some practice this line of code will be much easier to write.

 

There is an even shorter version of this statement and it uses the symbol ?: .

 

This version is called Elvis (do not ask me why) and consists in writing only the second expression.

 

 

In this case, if the condition is true and the ternary operator has to assign a variable it will be evaluated as 1.
 

This version is not suitable for testing, in fact, PHP will throw an error in this case

 

$var = true;
$result = (isset($var)) ?: " the variable is not set " ;
echo $result;
// $result will be 1

 

Here is a brief explanation on the ternary operator from Wikipedia.

 

 

 

Null Coalescing Operator

 

There is still another version of ternary operator (sort of) that is called a null coalescing operator or double question mark operator.

 

You will recognize it by the symbol ?? .

 

It allows verifying a condition with an even cleaner syntax through the use of two question marks.

 

It is possible to assign a value to a variable if the variable in question has been set previously and is not null.

 

Since the null coalescing operator reports no errors when you use it, it is better to use it instead of using the Elvis operator

$result = $var ?? "Hello";

 

As you can see from the previous example if the variable present in the first expression has been set then the $result variable will take that value, otherwise, PHP will give the value to the right of the Operator Null Coalescing, in this case, the string "Hello".

 

This function also applies to multiple Null Coalescing Operators,


It can be chained one after another giving life to a series of conditions, as for the single, in PHP parser will follow the expressions on the right until it finds a valid value.

 

$result = $var ?? $var2 ?? "Hello";

 

 

Spaceship Operator

 

Here is one of the operators preferred by PHP programmers, if nothing else, for its shape.

 

The spaceship operator is used to analyze and compare two different values and is extremely useful for example when data must be ordered.

 

The spaceship operator can return three different values.

 

These are -1, 0 and 1.

 

These values depend on the operands.

 

If the operand on the left is less than the operand on the right then the spaceship operator will return -1 if the two values are equal it will return 0 if the second operand (the one on the right) is greater than the first operand (on the left) the value returned from spaceship operator will be 1.

 

The spaceship operator also works in case you want to operate on strings, in fact, it is very useful for sorting words and letters.

 

Keep in mind that with the same letter the one with the smaller format will be considered major while the capital letter will be considered the minor.

 

see the examples below.

1 ⇔ 0 // it will result in 1
1 ⇔ 1 // it will result in 0
1 ⇔ 2 // it will result in -1
"variable" ⇔ "Variable" // it will result in 1

 

Have a look at the official manual for more about spaceship operator in PHP

 

 

 

Bitwise Operators

 

Bitwise operators work on integer bits.

 

They are represented in binary form.

 

There are three bitwise operators,

 

The first is the AND operator which has a bit set if both operands are set then we have the bitwise OR operator which instead will have the result set if one or both of the operands has a set bit.

 

Finally,

 

we have the bitwise operator XOR which will have the result bit set only if one of the operands has the bit set, not both
 

 

The result of this operation is simply the value we obtain after implementing these rules.

 

I understand that this may seem like a very complicated concept.

 

To make this concept simpler, you can think of these operations as if they represented a few decimal numbers.

 

You can calculate the binary representation of the numbers simply by comparing from right to left and then convert to decimal when you finished.

 

To make the concept even clearer below I will illustrate an example shown by the author Andrew Beak.

 

Taking into consideration two numbers 50 and 25,

 

To these two numbers, we implement the operator Bitwise AND.

 

As you can see,

 

following the rules are shown in precedence, as a result, we obtain the value 16,

 

When we check the number the result is shown and an integer.
 

 

Now I will show one of the weirdest operators in the whole PHP repertoire.

 

You'll read about Bit shifting!

 

Bit shifting allows you to shift the bit pattern by value, you can choose to do either from the right or from the left side.

 

To understand how Bit shifting works, think of a number as if it is shown in its binary form.

 

If the reference is to the right the operator is called "Shift Right" and a bit is moved from the right side,

 

if instead,

we use the "Shift" Left "the operation will add a zero in the right part of the binary representation of the number in question.

 

50
// Result in Binary 00110010

50 >> 1
// Result in binary: 0011001
// Result in decimal 25

50 << 1
// Result in binary: 01100100
// Result in decimal 100

 

Eventually, we have bitwise not operator.

 

This instead is very simple to understand, to find the result of this bitwise operator just find the binary value of a number and reverse the 1 in 0 and vice versa.

 

You will find great help in the base_convert() function that outputs the binary representation of a decimal number

 

To help you understand more about the concept of bitwise and bitwise operator, I have included an amazing video created by EpicFactFind below.
I hope you enjoy

 

 

 

Conclusion

 

What an interesting topic, isn't it?

 

I personally believe that PHP operators are the fundaments of every programming language.

 

They are indispensable and, as you will see in the next chapters of this series (subscribe to my newsletter to get notified when published), you will make extensive use of them in control structures and other operations.

 

 

As you've seen, some of them are really simple (I'm sure you have not had any trouble figuring out how to make an addition between two variables) but others like the "Elvis" operator or bitwise operations can create problems even for experienced programmers,

 

Nonetheless,

 

they are topics required in important exams such as the PHP Zend certificate.

 

 

As you know, the main purpose of this series of blog posts, like others on my website, is to give you an extra kick to let your skills skyrocket, and with them your career.

 

 

As always,

 

if something is not clear to you and you want clarification on something written in this post feel free to send me an email or, even better, take advantage of the community on Facebook for help. link below.

 

PHP basics for expert web developers (1' part)
Construct and Comments of PHP 7
How to use variables (PHP 7)
Composite variable in PHP (Arrays, Object and more)
PHP operators (part 1)
PHP Operators (part 2)
Conditional Structures in PHP
Loops in PHP(Tutorial)

...

 

Now you know the basics, it is time to start practising,

Take advantage of the power and the speed of Blue Host and create an account where you can exercise and see your improvement on a live server at less than a Starbuck's Caffe Mocha per month.

(This is an affiliate link, The price stays the same for you and it helps me improve this content.)

 

 

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (Php 7.x) Jan 2, 2019

Composite variable in PHP (Arrays, Object and more)

Get the full article See details
Coding (Php 7.x) Jan 11, 2019

PHP Operators (part 2)

Get full article See details
Coding (Php 7.x) Jan 21, 2019

Conditional Structures in PHP

Improve your skills See details
Get my free books' review to improve your skill now!
I'll do myself