Fast assignation of a php value

Fast PHP assignation of a default value.

Let's say the next exercise.


The code will work if we open the website and we send a value /example.php?id=20

But what if the argument id is missing.

Notice: Undefined index: id in example.php on line 3

It is because we are trying to read an index of the array that it does not exist.

What we could do?

Validating if the information exists.

if(isset($_GET['id'])) {
    $id = $_GET['id'];
} else {

While it works but it is verbose. What if we need to validate +30 arguments?

Ternary operator

We could use a ternary operator

$id=isset($_GET['id']) ? $_GET['id'] : null;

Null coalesce

If we use PHP>=7.0 then we could use the operator "??". Its short than the ternary operator but it requires PHP over 7.0, so if you are targeting old PHP, then you can't use it.

$id=$_GET['id'] ?? null;

Note, both ternary operator and null coalesce have the same performance.

@ symbol

The symbol @ is used to ignores errors. So, if the value does not exist, then it assigns the default value null.


However, it impacts the performance considerably (if you are doing a high demand site)

Another alternative

In all the other exercises, we are doing the next operation, if the index exists in the array, then we return the value in the index.. If not, then we return null. In any case, we assign a value to $id But what if we don't want to assign the value (if has not set). We could do the next code

if(isset($_GET['id'])) {
    $id = $_GET['id'];
} // if not, then $id could be indefined.

But again, it is verbose.

We could do the next operation

Boolean operator

isset($_GET['id']) and $id=$_GET['id'];

What? why?

First, it is insanely fast. Take note that isset() is not a function but a language construction.

But how it works?

Lets say this code

if($a && $b) {
    echo "both are true";

The if is evaluated as follow. If the first expression ($a) is true, then it evaluates the second expression $b. If $a is false, the $b is never evaluated, because the result of the whole expression is already false, no matter the value of $b.

Also, in PHP, we could use the operator && or "and", also we could use || or "or". Commonly we use the symbols && and || in a conditional branch and "and"/"or" in code.

About Jorge Castro

Currently: Entrepreneur and Private Consultant
Civil Engineer in Informatics - USACH Chile.
Master in Business Administration (MBA) CEPADE Spain
Microsoft Certified Professional
Oracle Certified Associate
ScrumMaster Certified
Former developer
Former Project Manager

Related Posts