If Else, and Elseif in PHP

Hi.. today we’ll learn and discuss if else in PHP along with elseif. As it meanings, the if statement will evaluate conditions, if the condition is TRUE then the if block will be executed, otherwise, the else block will be executed.

The if, else and elseif logic flow can be described in the following flow chart:

Understanding If Else in PHP as well as Elseif

I. If Else In PHP – The Writing rules

If else in PHP can be written in the three ways:

  1. Using Brackets: if ( expression ) { statement }
  2. Using colon: if ( expression ): statement endif;
  3. Not Using Both: if ( expression ) statement;

In Addition, there is also a short way to write it using the “ternary operator” (?:), to find out more, please visit this article: If Else on PHP using ternary operator ( ?: )

Code example:

1. Using Brackets

if ($name == 'john') {
	echo $name;
} else {
	echo $id;
}

2. Using colon

if ($name == 'john'):
	echo $name;
else:
	echo $id;
endif;

3. Not Using Both (Brackets and colon)

if ($name == 'john')
	echo $name;
else
	echo $id;

4. Using elseif

// Using Braces
if ($name == 'john') {
	echo $value;
} elseif ($name == 'doe') {
	echo $value2;
} elseif ($name == 'smith') {
	echo $value3;
} else {
	echo $value5;
}

// Using Colon
if ($name == 'john'):
	echo $value;
elseif ($name == 'doe'):
	echo $value2;
elseif ($name == 'smith'):
	echo $value3;
else:
	echo $value5;
endif;

II. Some Consideration

a If Else that only have ONE statement to execute can be written without brackets or colon

The if statement can be used stand-alone, without else or elseif, and if it only one statement, then it can be written without brackets or colon

For example:

/*
	Result: doe
*/
$first_name = 'john';
$last_name  = 'doe';

if ($first_name == 'thomas')
	echo $first_name;
echo $last_name;

The above example will give result: doe, because the if statement only read the echo $first_name; statement after evaluating the conditional expression. the following line echo $last_name; will treat as another general PHP script.

b The benefit of using colon

if our code is quite long, then it will be easier to use a colon to identify the end of the if statement, especially when it combined with HTML program, for example:

<?php
if ($post['id'] == 2) :?>
	<h1 class="post-title"> <?=$post['title']?></h1>
	<p class="post-content"> <?=$post['content']?></p>
	<div class="comments-container">
		<ul>';
		<?php
		foreach ($comment[$post['id']] as $comment) :
			if ($comment['publish'] == 3)
				continue;
			?>
			<li>
				<p class="comment-title"><?=$comment['title']?></p>
				<p class="comment-content"><?=$comment['content']?></p>		
			</li>
		<?php endforeach; ?>
	</div>
<?php endif;?>

c elseif or else if?

While writing if else statement, you are free to use either elseif or else if. BUT, important to note that if you use colon then you have to use elseif rather than else if, otherwise an error will occur. some example:

$value = 7;

if ($value >= 9) 
	echo 'Excellent';
else if ($value < 9 && $value >= 7)
	echo 'Good';
else if ($value < 7 && $value >= 5)
	echo 'Average';
else
	echo 'Poor';

if ($value >= 9) : 
	echo 'Excellent';
elseif ($value < 9 && $value >= 7) :
	echo 'Good';
elseif ($value < 7 && $value >= 5) :
	echo 'Average';
else :
	echo 'Poor';
endif;

d Is it possible to combine brackets and colon?

While writing if else statements in PHP, important to note that you cannot combine bracket with colon in ONE if else statement, you have to use one of them, otherwise you will encounter an error, for example:

$value 	  = 9;
$value2   = 8;

// Error
if ($value >= 9) :
	echo 'Excellent';
else { 
	echo 'Average';
}

// Good
if ($value >= 9) :
	if ($value2 >= 9) {
		echo 'Excellent';
	} else {
		echo 'Good';
	}
else:	
	echo 'Average';
endif;

III. Writing Standard

According to PSR-2 (PHP Standard Recommendation) defined by FIG (Framework Interoperability Group), you should write if else statement in the following form:

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

example:

if ($a != 2 && $a > 0) {
    $a = 2;
} else {
    $a = 7;
}

Explanation:

  • Use elseif instead of else if
  • Use braces instead of colon
  • The statement is written exactly one line below the expression.
  • Each expression should be separated by a space ( $a != 2 && $a > 0 ), making it more readable.

IV. Some Useful Tips

There are some useful tips while writing if else in PHP:

  1. While writing expressions, first write an expression which uses and (&&) operator, because if this condition is FALSE, then PHP does not evaluate the next expression, this will make the code run faster. for example:
    if ( 
    	$value > $value2  
    	&& ( $value <= $value3 
    		|| $value > $value4 
    		|| $value <= $value5
    	)
    )
    {
    	$html = '<span class="average-grade">'.$value.'</span>';
    }

    if the expression: $value > $value2 return FALSE, then the rest of expression will not be evaluated, and PHP will skip the if block.

  2. If you use a lot of elseif, then consider using a switch/case statement, because it has many advantages, such as faster code execution, code logic is easier to understand, and the code maintenance become easier.

Leave a comment

Like Us

Social