PHP if statement

The PHP ‘If’ comes into action wherever options come. Where there are more than one options for anything for any matter we have to decide.

In programming, we use one of the methods to handle this is by using the If and if-else PHP statements, also known as the decision making statements – to take decisions based on different situations.

See an example of if statement

Types of decision-making statements in PHP

There are three types of decision-making statements in PHP. Each of these types is explained below with an example.

An example of if..elseif..else

The if else statement

The if PHP statement is used when there are only two options or outcomes for any situation. For example, choose head or tail. If the head comes then you win otherwise you loose. Each situation has its own course of action.

In situations where there are only two possibilities, you can place one block of code in the if statement when the condition is true and (optionally) place the other block of code if the condition is false in the else block.

The if…else Syntax

The if example

Experience this example online

You can see, the if statement can be used in PHP without the else statement.

Execute more than one lines example

You can execute more than one lines in the if statement by using the curly braces as shown below:

Experience this example online

The if else example

Following is a PHP if else example:

Experience this example online

PHP elseif statement

Use the elseif statement where you have more than 2 situations to execute the code. You will initiate the if by using the if statement followed by a block of code to execute. After that, the other condition is enclosed in the elseif and so on.

Finally, you can place the else statement. When all conditions are false the else block of code will execute. See the elseif syntax and example below:

Syntax of using the elseif statement

Following is the syntax of using the elseif PHP statement:

The elseif Example

Following is the elseif example:

Experience this example online

The Switch Statement

Use this option when you have many options and have to execute one of those. To learn about PHP Switch go to its own chapter.