Google News
logo
PHP if...elseif...else statement
The `if...elseif...else` statement is a conditional statement in PHP that allows you to execute different blocks of code based on multiple conditions. Here's the basic syntax of an `if...elseif...else` statement :
if (condition1) {
    // Code to execute if condition1 is true
} elseif (condition2) {
    // Code to execute if condition2 is true
} else {
    // Code to execute if all conditions are false
}​
In this syntax, `condition1`, `condition2`, etc. are the expressions that you want to evaluate. The `if` statement checks if `condition1` is true. If it is true, then the code inside the first set of curly braces `{}` is executed, and the rest of the statement is skipped. If `condition1` is false, then the `elseif` statement checks if `condition2` is true. If it is true, then the code inside the second set of curly braces `{}` is executed, and the rest of the statement is skipped.

If both `condition1` and `condition2` are false, then the code inside the third set of curly braces `{}` is executed.

Here's an example of a PHP program that uses an `if...elseif...else` statement to test if a number is positive, negative, or zero :
Program :
<?php
	// This is a PHP program that uses an if...elseif...else statement to test if a number is positive, negative, or zero
	
	$num = 0; // A zero value
	
	if ($num > 0) {
		echo "The number is positive."; // Code to execute if the number is positive
	} elseif ($num < 0) {
		echo "The number is negative."; // Code to execute if the number is negative
	} else {
		echo "The number is zero."; // Code to execute if the number is zero
	}
?>
Output :
The number is zero.
In this code, the variable `$num` is assigned the value `0`, which is neither positive nor negative. The `if...elseif...else` statement then checks if `$num` is greater than `0`.

Since `$num` is not greater than `0`, the `elseif` statement checks if `$num` is less than `0`. Since `$num` is not less than `0` either, the code inside the third set of curly braces `{}` is executed, which prints the message "The number is zero." to the screen.

If `$num` had been assigned a positive or negative value, the code inside the corresponding set of curly braces `{}` would have been executed instead.

This demonstrates how `if...elseif...else` statements can be used to test multiple conditions and execute different code based on the result of each test.