PHP Tutorials: Conditional Statements

We all make a decision in our life based on specific conditions. The same we can do in any programming language. PHP also supports conditional statements. You can execute PHP statements based on conditions. If you remember we studied Conditional operators in our previous tutorial. Now we are going to continue with that in this tutorial. While using conditional statements. Conditional statement to work on boolean data type Which means true or false.

There are specific conditional statements available in PHP.

The if Statement

You always make a decision in your life, if you’re hungry you will eat food. Where anger is a conditional statement and having food is a script to execute. Same happens with PHP, Conditional statement evaluate if a particularly given statement inside if is true then it executes the given script inside the statement block.

Syntax:
<?php
	if( condition ) {
		statement 1;
		statement 1;
		...
		...
	}
?>
<?php
	$a = 10;
	$b = 15;
	if( $a < $b ) {
		echo "a is less than b."; //OUTPUT: a is less than b.
	}
?>

Here in this example, we see that the value of $a is less than the value of $b. The condition given in the statement is true and the PHP script gets executed.

The if..else Statement

In the if condition we always have a single option, the script gets executed only if the condition is true but in that, if..else statement we also have an option if the condition is not true.

Syntax:
<?php
	if( condition ) {
		Statement block;
	} else {
		Statement block
	}
?>
<?php
	$a = 15;
	$b = 12;
	if( $a < $b ) {
		echo "a is less than b.";
	} else {
		echo "b is less than a.";
	}
?>
OUTPUT: b is less than a.

The if..elseif..else Statement

Till now we are familiar with two types of conditional statements. But sometime in your applications, you will have to make a decision based on multiple conditions. The if..elseif ladder does this for you. You can have multiple conditions. But only one of these conditions will be true and that particular statement block will get executed.

Syntax:
<?php
	if( condition ) {
		Statement block;
	} elseif( condition ) {
		Statement block;
	} elseif( condition ) {
		Statement block;
	} else {
		Statement block
	}
?>
<?php
	$day = 5;

	if( $day == 1 ) {
		echo "Today is Monday.";
	} elseif( $day == 2 ) {
		echo "Today is Tuesday.";
	} elseif( $day == 3 ) {
		echo "Today is Wednesday.";
	} elseif( $day == 4 ) {
		echo "Today is Thursday.";
	} elseif( $day == 5 ) {
		echo "Today is Friday.";
	} elseif( $day == 6 ) {
		echo "Today is Saturday.";
	}else {
		echo "Hurry! Today is Sunday."; //OUTPUT: a is less than b.
	}
?>
OUTPUT: 
Today is Firday.

Leave a Reply

Your email address will not be published. Required fields are marked *