PHP Operators (part 2)

Written by anastasionico | Published 2019/01/15
Tech Story Tags: programming | php | operators | equality | php-development

TLDRvia the TL;DR App

Introduction

Operators in PHP are a vast subject and not always fully understood.

One of the reasons for all these misunderstandings is that some operators are very simple and can be implemented in the code within seconds after reading about them,

Others instead,

are almost unknown and, once studied, it is still better to use them sparingly.

Although operators belong to the category “basics of language”, a misuse utilization of them or a typo while using them is very difficult to identify.

It may happen to lose more than half an hour of your time just trying to debug some code and then discover that the symbol of equality had been inserted instead of the one of inequality.

Personal experience (Sigh).

After you have discovered the main types of PHP operators in my previous blog post.

Below you will see the reference operator, assignment operators and some goodies that you can use to impress 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 7How to use variables (PHP 7)Composite variable in PHP (Arrays, Object and more)PHP Operators (Part 1)PHP Operators (Part 2)

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

Assign OperatorReference OperatorComparison OperatorError-Control OperatorBacktick OperatorConclusion

Assign Operator

As you have seen in the last chapter,

unless you need empty or null variables, every variable should have a value.

but how do we assign a value to a variable?

In order to assign a value to a variable, PHP provides to web developers a number of operators called assignment operators.

They take as their basis the equal symbol “=”.

The syntax consists of three factors:

The first is the variable indicated by its name, in the middle, there is the assignment operator, the third element of the statement is the value that, can be of different type.

Here is an example:

$variable = “this is a string”;

The assignment operator can be combined with any other binary and arithmetic operators giving the programmer a way to make his code faster to write and easier to read.

Here are some examples of compound assignment operators:

$sum = 1 + 1; $sum += 100;// this is equal to $sum = $sum + 100;// $sum is equal to 102;$string = "My name is:";$string .= "Nico";// this is equal to $string = $string . "Nico";// $string is equal to "My name is Nico

A common mistake and something that even experienced programmers must always pay attention is to write the assignment operator when they mean the equal operator “==”.

Just think of incorrect use of the latter in a consensus like an if statement,

$var = "Hello";if ($var = "Goodbye") {}

While with an equality operator the result of this condition would be false, in this case, the variable $var is correctly assigned the new value “Goodbye” so the PHP parser evaluates the condition as true.

A technique to avoid this mistake used by some experts is the so-called Yoda Condition,

This convention takes advantage of the fact that PHP does not allow you to change the value of a constant,

If you put a constant on the left side of the condition PHP will throw a warning if you make an error while writing the code.

Although it is proven that this technique works, it is up to you to decide whether it is worthwhile using it in a condition of readability and personal style.

Reference Operator

Here is one of the most strange and difficult to understand symbols that I have encountered in my path towards the mastery of language (which is still far from the arrival).

In PHP there are two different ways to use assignment on a variable,

by value or by reference.

By default, all scalar values are assigned by value,

If you want to assign a scalar value via reference it is possible to use the symbol =&

$firstPerson = "Nico";$secondPerson =& $firstPerson;$secondPerson = "John";echo $firstPerson;// The value echoed out will be "John" instead of "Nico"

For objects,

exactly the opposite happens,

all the objects are always assigned by reference,

If you try to use the =& symbol of a PHP object it will throw an error.

Confused?

Here is the explanation,

This difference happens because after years of development and improvement PHP has optimized this process making the assignment of variables as fast as possible.

This is possible through the use of a container called zval,

Zval is made up of four parts:

value, type, Is_ref and Refcout.

This container contains all the info of a variable such as a length, size, exact position in memory.

When we call a value by reference we are indicating the exact element that contains its value.

Here is a detailed explanation of these containers

Comparison Operators

Time for homework …

Is one equal to one?

Stop for a minute and write this last sentence in PHP,

Done?

Let’s see the result.

In order to do the previous operation, you need PHP features called comparison operators.

To be precise, there are 9 elements in this category and they are all very simple to learn.

In fact,

you’ve already learned many of them from elementary school.

To make a comparison, you need one of the symbols and two elements to compare each one placed next to the symbol:

Here are the operators:

Greater than: symbol > For the condition to be true, the element on the left must be larger than the element on the right, (this is not only for numbers but also for strings considering the alphabetic position and the capital letters count as less than the lower case).

Greater than or equal to: symbol >= enough explicative right?

Less than: symbol < exactly the opposite of Greater than

Less than or equal to: symbol <= the opposite of Greater than or equal to

Not equal: symbol <> To be true, the two values must be different

Equivalence: symbol == To be true, the two values must NOT be different

Identity: symbol === To be true, the two values must not only have the same value but must be of the same type

$int = 123;$str = "123";($int === $str)// the result of this condition is false because although the values ​​are equal the two types of variable are different

Not equivalent: symbol != see <>

Not identical: symbol !== In a certain way, this one can be identified with the identical operator ===,

The result of this statement is true if the two elements we are comparing do not have the same value and are not of the same type.

Note that if the two elements have the same value, but they are of two different types, they are not identical.

The same occurs if the two values belong to the same type but do not have two equal value.

Extra Operators

Here are two operators that are not seen often and the reason why this series is called “PHP basics for expert web developer”.

error control operator

Have you ever seen the @ operator?

This is called Error Control Operators and is used to suppress errors in PHP.

Here you will find more information about the error control operator

Now,

As you can imagine, hide errors is not considered good practice and makes the debugging process exponentially more difficult.

Why use this operator then?

Let’s make an example,

A little while ago I published a couple of articles in which I described the new features and deprecations of PHP 7.3.

One of the differences between the last and previous versions of this programming language concerns the preg_match() function and the regex that the function needs as one of the parameters.

If you have made heavy use of this function in your applications and still want to update the code to PHP7.3 instead of dealing with all the errors that will occur you can simply disable the errors,

update the server to the new version of PHP and fix the errors one by one.

Note that this operator works only if the library used by the function in question uses PHP standard error reporting.

Of course,

I do not recommend doing this, but I’m here to let you know that this option exists.

Here is an article, quite old but still topical, on the subject written by Derick Rethans the author of Xdebug.

It’s up to you to decide if and how to use it.

Here is an example of the syntax:

$db = @mysqli_connect();// Even if there will be an error with the connection no errors will be displayed

backtick operator

Another operator that is rarely used is the operator called “backtick operator”.

Using this operator is equivalent to using the shell_exec() command,

It executes a command required as a string as a parameter via the shell and if executed with success, returns the string itself.

echo `touch index.php`;// this command is equal to shell_exec('touch index.php');

An advice that I can give you and use these two commands sparingly,

Since we are talking about operations on the file system, it does not take a genius to understand the destructive power of these commands.

Use them carefully,

Sanitize the text and above all, never use external input like strings entered by users as a parameter.

Conclusion

I bet you feel overwhelmed? aren’t you?

It is normal.

Too much information all together can have this effect.

As I wrote several times during this series do not believe that it is necessary to learn everything you read at once.

Actually,

I think once you read this topic you should take your time to assimilate it all.

Do not get me wrong,

some of these operators are not difficult at all and I think it’s important to use them as soon as you finish reading this post.

For others instead, meh.

Rarely will you use them, on the contrary, following the best practices it is better not to use them at all.

One piece of advice I think is important to give you is to take note of this post (bookmark it if you will) and read it again and review what is written in it a couple of weeks from now.

Analyze which operators you used the most and which you do not use at all.

Then check whether the scripts you’ve used in recent weeks can be simplified using some of the operators described in these pages.

Here you have it!

You’ve just discovered the secret to learning and properly implementing every old and new feature of PHP.

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.)

Originally published at anastasionico.uk.


Written by anastasionico | anastasionico.uk
Published by HackerNoon on 2019/01/15