Google News
logo
PHP if statement
The `if` statement is a conditional statement in PHP that allows you to execute code only if a certain condition is true. Here's the basic syntax of an `if` statement :

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

Here's an example of a PHP program that uses an `if` statement to test if a number is positive or negative :
Program :
<?php
	// This is a PHP program that uses an if statement to test if a number is positive or negative
	
	$num = 5; // A positive 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 positive.
In this code, the variable `$num` is assigned the value `5`, which is a positive number. The `if` statement then checks if `$num` is greater than `0`. Since `$num` is indeed greater than `0`, the code inside the first set of curly braces `{}` is executed, which prints the message "The number is positive." to the screen.

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

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