PHP Free Tutorial

If Condition in PHP

In PHP, Programming by Baqir Ali

Whenever you want an application that should make a decision on some point we use if condition or statement.

Simple If Statement in PHP

Syntax:
if(condition)
   Do this;

In the above code, the Do this statement will either run or not run depending on whether the condition is true or false. The above If statement affects only a single line, but for multiple line, we use a block for the if condition. such as

if(condition)
{
    line 1;
    line 2;
    ......
}

Example 1:

<?php
	$age=25;
	if($age<40)
        {
		echo "You are Young";
                echo "Enjoy Your Life";
        }
?>

Output: You are Young Enjoy Your Life

The lines of code affected by the ‘if statement’ are put inside curly brackets.

The If-Else Statement in PHP

We use If-Else Statement when the condition is false we want another statement to run. like if age is above 40 the statement should be as ‘You are Old’.

Example 1:

<?php
	$age=20;
	if($age<40)
	{
		echo "You are Young";
		echo "Enjoy Your Life";
	}
	else
	{
		echo "Sorry! ";
		echo "You are Old";
	}
?>

Example 2: Use If-Else to find the max of two numbers

$num1=100;
$num2=20;

if($num1>$num2)
	$max=$num1;
else
	$max=$num2;
echo "Maximum is ".$max;

Else-If Statement

The else-If statement is used when we want to check multiple conditions instead of one.

Syntax:
if(Condition)
{
   //code;
}
else if(Condition 2)
{
   //code;
}
else
{
   //Will run when all conditions are false
}
<?php
	$salary=30000;
	if($salary>60)
		echo "Nice Job";
	else if($salary>40)
		echo "You may survive";
	else if($salary>30)
		echo "Find another Job";
	else
		echo "Bankrupt";
?>

Compound If Statement

We create compound if-statement using logical operators. Suppose if I want to make a grading system for students I will use compound statements.

<?php
	$m=65;
	if($m>90 && $m<=100) // it means if marks is between 90 and 100
		echo "A+";
	else if($m>80 && $m<=90)
		echo "A";
	else if($m>70 && $m<=80)
		echo "B";
	else if($m>60 && $m<=70)
		echo "C";
	else if($m>=50 && $m<=60)
		echo "Pass Only";
	else if($m>=0 && $m<50)
		echo "Fail";
	else //else part will run only if $m is not between 0-100
		echo "Invalid Marks Entered";
?>

Switch Statement in PHP

A switch/case statement is similar to an if statement, except that it can only check for an equality comparison of a single expression. We can not use a switch case with the compound statement.

switch (expression)
{
case 'a' :
      echo 'expression is a'; break;
case 'b' :
      echo 'expression is b'; break;
case 'c' :
      echo 'expression is c'; break;
default :
      echo 'expression is unknown'; break;
}

We use the break statement in order to stop checking another case otherwise it will keep checking and execute another statement that is without break.

Support us by sharing this post