Summary: in this tutorial, you will learn about the PHP if statement that allows you to execute a piece of code conditionally.
Simple PHP if
statement
The if
statement is one of the branching statements in PHP. The if
statement allows you to make decision based on one or more conditions and execute a piece of code conditionally. The following illustrates the syntax of the if
statement:
1 2 3 4 | <?php if (condition) { // put the code here; } |
The condition that follows the if
keyword is a Boolean condition, which evaluates to true
or false
. If the condition evaluates to true
, the code block inside the if
statement is executed.

PHP IF statement Flowchart
PHP if statement example
The following is an example of using the if
statement. We have $x
variable with value 11
. In the if
statement, we check if value of $x
is greater than 10
we display a message.
1 2 3 4 5 | <?php $x = 11; if($x > 10){ echo '$x is greater than 10'; } |
PHP if else statement
The if
statement allows you to run a block of code if the condition evaluates to true
. If the condition evaluates to false
, the if
statement skips the code block inside its body. You can enhance the if
statement by adding else
statement to run an alternative code block if the condition evaluates to false
.

PHP if else statement flowchart
The following illustrates the syntax of the if else
statement:
1 2 3 4 5 6 | <?php if (condition) { // execute if condition evaluates to true; }else{ // execute if condition evaluates to false; } |
PHP if else statement example
The following example demonstrates how to use the if else
statement:
1 2 3 4 5 6 7 | <?php $x = 2; if($x > 10){ echo "$x is greater than 10"; }else{ echo "$x is less than 10"; } |
PHP if elseif statement
If you have more than one Boolean condition to test, you can use the if elseif
statement. The following illustrates the if elseif
statement:
1 2 3 4 5 6 7 8 9 10 11 | <?php if(condition1){ // code block of if branch to be executed }elseif(condition2){ // code block of elseif branch to be executed }elseif(condition3){ // code block of elseif branch to be executed }else{ // code block of else branch to be executed } |

php if elseif statement flowchart
PHP if elseif statement example
The following is an example of using the if elseif
statement:
1 2 3 4 5 6 7 8 9 | <?php $x = 20; if($x > 0){ echo "$x is greater than zero"; }elseif($x == 0){ echo "$x is zero"; }else{ echo "$x is less than zero"; } |
PHP if statement with HTML code inside its body
If you want to output HTML code inside body of the if
statement, you can follow the example below:
1 2 3 4 | <?php $x = 10; ?> <?php if($x == 10) : ?> <p>This is HTML code inside if statement</p> <?php endif; ?> |
An if
statement can be nested inside another if
statement. This allows you to have a complete flexibility in controlling conditional execution of code.
In this tutorial, you have learned how to use PHP if
statement to control the code execution conditionally.