PHP IF ELSE ELSEIF conditional statements best practices

PHP IF ELSE ELSEIF conditional statements best practices. IF statement best practices for different conditions. When to use ternary operator, How to break long IF conditions in multi line, When to use switch case instead of IF.

No matter you are beginner or experience programmer in PHP, Given PHP IF ELSE ELSEIF conditional statements example will useful for all.

By using IF statement in best way, you can write clean, simple and readable PHP code.

PHP IF ELSE ELSEIF conditional statements best practices
PHP IF ELSE ELSEIF conditional statements best practices

Points for PHP IF ELSE ELSEIF conditional statements

IF statement format example

How write IF statement in PHP? Well It’s easy, but How to write IF statement in proper format?

Let’s look some example IF statement with format, means where to add space, when to add bracket etc.,

<?php
if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}

How to break long IF conditions in multi line

Long conditions, this is the case which comes now and than in programming.

Some business logic have too many rules and thats why in some cases required too many conditions in code.

Let’s check how to break long IF conditions in multi line with example, so, code looks readable and easy to understand.

<?php

//BEFORE
if (in_array($name, ['test', 'name']) && $age > 18 && $role == 'admin' && ($code == 'IN' || $code == 'UK') && ...) {
    // if body
}

//AFTER
if (in_array($name, ['test', 'name']) &&
    $age > 18 && $role == 'admin' &&
    ($code == 'IN' || $code == 'UK') &&
    $moreConditions) {
    // if body
}

When to use ternary operator instead of IF

It depends on condition length and complexity.

Means, If process is like to assign value to some variable based on some condition, you can use ternary operator.

PHP ternary operator is looks clean and simple, but in some complex condition, it not gives code readability.

You can use PHP ternary operator based on requirement and condition complexity.

e.g.,

<?php

$name = !empty($firstname) ? $firstname : $defaultValue;
$name = !empty($firstname) ? $firstname : (!empty($otherVal) ? $otherVal : $defaultValue);

When to use switch case instead of IF

When to use switch case instead of IF, ok, mostly i use switch case.

When some decision/set some variable/call some functions etc., required for different cases.

Decision process have normal conditions or variable assignment or some action.

Avoid using switch case when process is complex and have too many conditional statement and use IF statement instead, too write best code.

PHP IF ELSE ELSEIF conditional statements best practices – Conclusion

So, here is simple rules for PHP IF ELSE ELSEIF conditional statements which i follow and hope you like to use it.

For more detail, here are some useful links for you.
PHP > Control Structures > IF
PSR-2: Coding Style Guide
Some more PHP post