PHP if Statement

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:

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 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.

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

PHP if else statement flowchart

The following illustrates the syntax of the if else statement:

PHP if else statement example

The following example demonstrates how to use the if else statement:

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:

php if elseif statement

php if elseif statement flowchart

PHP if elseif statement example

The following is an example of using the if elseif statement:

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:

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.

  • Was this tutorial helpful ?
  • YesNo