Google News
logo
PHP if...else statement
The `if...else` statement is a conditional statement in PHP that allows you to execute one block of code if a certain condition is true, and another block of code if the condition is false. Here's the basic syntax of an `if...else` statement :

Syntax :
if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}
In this syntax, `condition` is the expression that you want to evaluate. If `condition` is true, then the code inside the first set of curly braces `{}` is executed. If `condition` is false, then the code inside the second set of curly braces `{}` is executed.

Here's an example of a PHP program that uses an `if...else` statement to test if a number is positive or negative :
Program :
<?php
	// This is a PHP program that uses an if...else statement to test if a number is positive or negative
	
	$num = -3; // A negative number
	
	if ($num > 0) {
		echo "The number is positive."; // Code to execute if the number is positive
	} else {
		echo "The number is negative."; // Code to execute if the number is negative
	}
?>
Output :
The number is negative.
In this code, the variable `$num` is assigned the value `-3`, which is a negative number. The `if...else` statement then checks if `$num` is greater than `0`. Since `$num` is not greater than `0`, the code inside the second set of curly braces `{}` is executed, which prints the message "The number is negative." to the screen.

If `$num` had been assigned a positive value, the code inside the first set of curly braces `{}` would have been executed instead, which prints the message "The number is positive." to the screen.

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