DEV Community

spO0q
spO0q

Posted on • Edited on

Best PHP practices explained

It might be hard for beginners to understand why some practices are safer.

Some of the following tips might go beyond PHP though.

Always use curly brackets

Let's have a look at the following code :

if (isset($condition) && true === $condition) 
    echo 'this is a success';
Enter fullscreen mode Exit fullscreen mode

No PHP error but what happens with :

if (isset($condition) && true === $condition) 
    foreach (range("A", "Z") as $letter)
        echo $letter . PHP_EOL;
        echo 'this is a success';
Enter fullscreen mode Exit fullscreen mode

Still, no PHP error and "this is a success" appears only 1 time in the end, as probably intended, that was a trap :)

Hum... wait! No PHP error but what happens if you write $condition = false; before :

this is a success

Crap! We don't want that. Do you see now why curly brackets are important?

Omitting brackets often leads to unwanted side effects. Besides, it's much harder to read code. So write this instead :

$condition = false;
if (isset($condition) && true === $condition) {
    foreach (range("A", "Z") as $letter) {
        echo $letter . PHP_EOL;
    }
    echo 'this is a success';
}
Enter fullscreen mode Exit fullscreen mode

Skip the else part

It's good practice to initialize any variable before using it. Considering the following :


if (isset($condition) && true === $condition) {
    $main = 'chocolate';
} else {
    $main = 'vanilla';
}
Enter fullscreen mode Exit fullscreen mode

you might think that's ok but what if you add several elseif conditions :

if ($condition) {
    $main = 'chocolate';
    $time = 2;
} elseif($otherCondition)) {
    $main = 'strawberry';
    $time = 3;
} elseif($otherOtherCondition)) {
    $main = 'apple';
    $time = 1;
} else {
    $main = 'vanilla';
    $time = 9;
}
Enter fullscreen mode Exit fullscreen mode

The code is already heavy. There's a good chance you will forget some vars somewhere when adding logic inside each elseif.

Instead write :

$main = 'vanilla';
$time = 9;

if ($condition) {
    $main = 'chocolate';
    $time = 2;
} elseif($otherCondition)) {
    $main = 'strawberry';
    $time = 3;
} elseif($otherOtherCondition)) {
    $main = 'apple';
    $time = 1;
}
Enter fullscreen mode Exit fullscreen mode

This way, everyone knows $main and $time should be defined all the time. The code seems more readable.

Don't use the @ operator

It's an error control operator in PHP. It hides errors but nobody wants that.

Instead, you should try to catch errors and use error logs.

This operator has huge drawbacks such as turning any debug into a nightmare or making the code slower!

For each run of your code, it will invoke the INI settings to set the error_reporting to 0 and set it back to its original value after.

Such a waste of resources. I think it's safer not to use it at all.

Some thoughts about ternaries

While ternary operators might be handy, the code may be harder to read.

Don't overuse ternary operators

Ternaries allows shortcutting the if-else part :

$main = ($condition) ? "chocolate" : "vanilla";
Enter fullscreen mode Exit fullscreen mode

which means :

if ($condition) {
    $main = "chocolate";
} else {
    $main = "vanilla";
}
Enter fullscreen mode Exit fullscreen mode

This one is ok but I've already seen the following :

$output = ($condition) ? ($otherCondition) ? 'ok' : 'ko' : 'unknown';
Enter fullscreen mode Exit fullscreen mode

Neither chaining nor nesting ternaries are recommended.

Use "Elvis" operator with caution

The Elvis operator is a special one.

$foo = $bar ?: "baz";
Enter fullscreen mode Exit fullscreen mode

The above means :

$foo = $bar ? $bar : "baz";
Enter fullscreen mode Exit fullscreen mode

which can be written like that :

if ($bar) {
    $foo = $bar;
} else {
    $foo = "baz";
}
Enter fullscreen mode Exit fullscreen mode

Believe it or not, as the wiki said :

The name "Elvis operator" refers to the fact that when its common notation, ?:, is viewed sideways, it resembles an emoticon of Elvis Presley with his quiff.

Be careful with the null coalescing operator

The null coalescing operator has been available since PHP 7 :

syntactic sugar for the common case of needing to use a ternary in conjunction with isset().

So :

$result = isset($_GET['result']) ? $_GET['result'] : "default";
Enter fullscreen mode Exit fullscreen mode

can be written like that :

$result = $_GET['result'] ?? "default";
Enter fullscreen mode Exit fullscreen mode

Be extra careful when trying to replace ternaries and Elvis operators with null coalescing operators!

The null coalescing operator never checks if a condition is true, it is meant to check if your var is set and not null (the very concept of isset()).

Wrap up

I hope you enjoy these programming tips. The last thing I want to say is: Please don't sacrifice clarity just for the sake of brevity.

Top comments (6)

Collapse
 
kevin_fr profile image
kevin

Thanks for the good article

else can be refactored with function i think

Collapse
 
dhayalramk profile image
Dhayal Ram

Nice article, Thank you

Collapse
 
mchojrin profile image
Mauro Chojrin

What about Yoda expressions?

Collapse
 
snesi profile image
David Domingo

Nice and clear Julien! Thank you!

Collapse
 
josemadis profile image
Josema Aranda

Very nice and helpful info.
Thanks, Julien

PS: My first comment in DEV :D

Collapse
 
wapcrazut profile image
Williams Abraham

Always use curly brackets! This is something I've been discussing with some work colleagues, they think is better without it but this is a very common error. Thanks for sharing it with the world!