Web Programming TutorialsPHP If...else Statement

PHP If…else Statement

Each language has statements that control its execution. These statements are called as control statements. These statements control the decision making, repetition, interruption etc. in the execution of the program. In this tutorial we will see one such decision making statement called as If…else statement. This statement is also called as conditional statement. Different decisions are taken based on different conditions. If…else statement has different forms. Let us see all the forms one by one.

  1. If statement:
    • The purpose of If statement is to check a condition.
    • Let us see the syntax of if statement.
    • if(condition)
      {
      	Statement(s);  //code to be executed
      }
    • In the syntax if is the keyword and a condition is given in the parenthesis following if keyword.
    • The opening and closing curly braces denote the start and end of the if block.
    • This if block can contain one or more statements.
    • When the condition in the if statement evaluates to true, the statements in the if block are executed.
    • If the if statement has only one statement to be executed if the condition evaluates to true then the curly braces can be omitted.
    • Create a new folder if_else in htdocs folder of xampp folder in C drive and then save a notepad++ document with name index.php in this newly created if_else folder.
    • Let us see an example on if statement.
    • Imagine that you are working in a company. The company has decided to give Rs. 2000/- as diwali bonus to employees whose service is more than or equal to 5 years. How will we check this in if statement, let us see.
    • Write the following code in this index.php file.
    • <html>
      <head>
      <title>If....else statement</title>
      </head>
      <body>
      
      <h2>Demonstration of if statement</h2>
      
      <?php
      $nyrs=6;
      
      	if($nyrs>=5)
      	echo 'You will receive Rs.2000/- as diwali bonus.';
      ?>
      </body>
      </html>
      
    • We have embedded PHP code in HTML.
    • Here in the above code PHP code in written in the PHP tag in body section.
    • We know that to receive diwali bonus it is must that the employee has completed 5 or more than 5 years of service.
    • For example we took 6 years and stored it in the variable $nyrs.
    • Now to check the condition we use if statement.
    • The condition is that the number of service years should be 5 or more than that, so the condition checked in if statement is $nyrs>=5 i.e. the comparison operator greater than or equal to is used to check if the number of years given are greater than or equal to 5.
    • Condition in the above example evaluates to true, hence the statement You will receive Rs.2000/- as diwali bonus. is displayed.
    • You will notice that curly braces are not given around the echo statement, this is because the if statement has only one statement to execute after checking the condition i.e. the echo statement. For one statement we can eliminate the curly braces but we cannot eliminate them if the if block has more than one statements. This rule should be followed with all the control statements.
    • The output is shown below in browser when you put the address localhost/if_else in the address bar of the browser:
    • if_stmt_output
      fig 1

    • But if the number of years of service is less than 5 then you will get no output.
    • Try taking value 4 in the variable $nyrs in the above example.
    • You will get no output and hence you will not understand anything.
    • In such cases when we want answer for both conditions i.e. even if the condition evaluates to true or it evaluates to false, we use if…else statement.
    • In if statement we get answer only when the condition is true, but in if…else statement we get answer for true as well as false condition.
  2. If…else statement:
    • If…else statement is used to check a condition and execute the statements accordingly.
    • Let us first see the syntax of if…else statement.
    • if(condition)
      {
      	Statement(s);  //code to be executed
      }
      else
      {
      	Statement(s);   //code to be executed
      }
    • In the syntax if and else are the keywords and a condition is given in the parenthesis following if keyword.
    • As opening and closing curly braces below if statement denote the start and end of the if block, the opening and closing curly braces below else statement denote the start and end of the else block.
    • Each block can contain one or more statements.
    • When condition in if statement evaluates to true, the statements in the if block are executed. But when condition in the if block evaluates to false, the statements in the else block are executed.
    • Let us see an example on if…else statement.
    • Let us find whether a given number is even or odd.
    • Write the following code in this index.php file.
    • <html>
      <head>
      <title>If....else statement</title>
      </head>
      <body>
      
      <h2>Demonstration of if...else statement</h2>
      
      <?php
      $no=10;
      
      	if(($no%2)==0)
          {
      		echo '<strong>The number '.$no.' is even</strong>';
          }
      	Else
          {
      		echo '<strong>The number '.$no.' is odd</strong>';?>
          }
      </body>
      </html>
      
    • In the above code we are given a number 10 in variable $no.
    • Our purpose is to check whether the given number is even or odd.
    • We check the condition in if statement.
    • How is the condition checked? We know that when any number is completely divisible by 2 it is an even number otherwise it is odd.
    • Keeping same thing in mind we first divided the given number by 2 and obtained its remainder using modulus arithmetic operator (%), as we know that we can get remainder of any division with the use of modulus operator.
    • Next we equated the remainder obtained with zero (0). If both are equal, it means the condition has been satisfied and evaluated to true i.e. the given number is even.
    • As the condition is true the statement in the if block is executed.
    • The output is shown below:
    • if_else_stmt_output_1
      fig 2

    • Now if I changed the number in variable $no from 10 to 11.
    • The condition in the if statement will evaluate to false and statement in the else block will be executed.
    • The output is shown below:
    • if_else_stmt_output_2
      fig 3

    • Now in the above if and if…else statement we checked only one condition but we can check more than one conditions by using if…elseif…else statement.
  3. If…elseif…else statement:
    • If…elseif…else statement is also called as if…elseif ladder.
    • It is used to check more than one conditions at a time.
    • This form of if…else contains if, else and elseif keywords.
    • The syntax of if…elseif…else statement is shown below:
    • if(condition)
      {
      		Statement(s);  //code to be executed
      }
      elseif(condition)
      {
      		Statement(s);  //code to be executed
      }
      elseif(condition)
      {
      		Statement(s);  //code to be executed
      }
      -
      -
      -
      else
      {
      		Statement(s);  //code to be executed
      
      }
      
    • In the above syntax we can see that first condition is checked in the if statement and the later conditions are checked in each elseif statement.
    • It executes in the following way:
      • At the beginning first condition is checked in the if statement.
      • If the condition evaluates to false, the control goes to the elseif statement below the if block. The condition in this elseif statement is checked. If this condition evaluates to true, the statements in its block are executed otherwise the control goes to the next elseif statement.
      • In the next elseif statement the same thing is done.
      • In this way if all the elseif statements present evaluate to false, the statements in the else block are executed.
    • The number of elseif statements depend on the number of conditions.
    • Let us see an example on if…elseif…else control statement.
    • Let us decide the grade of a student depending on the percentage obtained in his exam.
    • Write the following code in this index.php file.
    • <html>
      <head>
      <title>If....else statement</title>
      </head>
      <body>
      
      <h2>Demonstration of if...elseif...else statement</h2>
      
      <?php
      
      //demonstration of if...elseif...else statement
      $per=60;
      
      	if($per>=65)
      	{
      		$grade='A+';
      		echo "<strong>Congratulations! You secured ".$grade." grade.</strong>";
      	}
      	elseif($per<65 && $per>=60)
      	{
      			$grade='A';
      		echo "<strong>Congratulations! You secured ".$grade." grade.</strong>";
      	}
      	elseif($per<60 && $per>=55)
      	{
      			$grade='B+';
      		echo "<strong>Congratulations! You secured ".$grade." grade.<strong>";
      	}
      	elseif($per<55 && $per>=50)
      	{
      			$grade='B';
      		echo "<strong>Congratulations! You secured ".$grade." grade.</strong>";
      	}
      	elseif($per<50 && $per>=45)
      	{
      			$grade='C';
      		echo "<strong>Congratulations! You secured ".$grade." grade.</strong>";
      	}
      	else
      	{
      		echo "<strong>Sorry, you failed!</strong><br>";
      		echo "<strong>Study hard</strong>";
      	}
      ?>
      </body>
      </html>
      
    • In the above code, we want to find out the grade secured by the student on the base of his percentage.
    • Percentage of the student i.e. 60 are given in the variable $per.
    • In the if…elseif…else statement we check every possible condition to find out the grade.
    • First we check if the value of $per is greater than or equal to 65, if it is so then the student gets A+ grade and it is printed on the webpage.
    • Next if the first condition doesn’t satisfy then the next condition is checked. In this next condition it is checked whether the value of $per is in between the range of 60 and 65. The conditions are $per<65 and $per>=60 and a logical operator, logical and (&&) is used between the two conditions. This && indicates that both the conditions must be true to evaluate the condition to true.
    • But if this condition fails, the same thing is done with the next condition and so on.
    • In the above code the condition ($per<65 && $per>=60) is satisfied and hence we get the output
    • Congratulations! You secured A grade.
    • The output is shown below:
    • if_elseif_else_stmt_output_1
      fig 4

    • If we change the value of $per from 60 to 43, then no condition will be satisfied since 43 occurs in not even one range given in the conditions.
    • This will take the control directly to the else part. Then the output will be as shown below:
    • if_elseif_else_stmt_output_2
      fig 5

  4. Some more examples:
  5. We will study some more examples to understand how to check conditions and how to write code in the if-else blocks.

    • Writing condition:
      • To write a condition we use different operators to compare and calculate the values given.
      • But for this you need to know purpose of each operator, then you can use it in correct place.
      • We have used different comparison operators in the above examples and have also used logical and (&&) operator in the above if…elseif…else statement. Now we know that if && is used, it means all the conditions joined by it should be true.
      • Similarly we will see a logical or (||) operator in the example below:
      • We are going to check whether the given character is a vowel or a consonant.
      • Write the following code:
      • <html>
        <head>
        <title>If....else statement</title>
        </head>
        <body>
        
        <?php
        
        //demonstration of logical or oper. in if...else statement
        
        $c='e';
        
        	if($c=='a' || $c=='e' || $c=='i' || $c=='o' || $c=='u')
        	{
        		echo"<strong>’".$c."’ is a vowel.</strong>";
        	}
        	else
        	{
        		echo"<strong>’".$c."’ is a consonant</strong>";
        	}
        
        ?>
        </body>
        </html>
        
      • In the above example we checked whether the value of $c variable is equal to ‘a’, or it is equal to ‘e‘ or it is equal to ‘i’, or ‘o’ or ‘u’. That means the condition will evaluate to true even if one of the character matches with the value of $c.
      • Since variable $c has character ‘e’ assigned to it, it satisfies the condition and returns the statement e is a vowel.
      • If variable $c has some other character, other than the vowels say ‘s‘, it will return statement s is a consonant.
      • The output is shown below:
      • vowel_or_consonant_output
        fig 6

    • Code in if else block:
      • Note that we have used only echo statements in if-else blocks in the above examples.
      • But it is not so that we have to use only if else statements in the if-else blocks. We can do anything once the condition is written. i.e. we can print something, calculate something, we can even call a function in if-else blocks.
      • Let us try an example.
      • We will calculate final bill of bags purchased from a shop. Imagine that the shopkeeper gives 10% discount on the quantity of bags purchased greater than or equal to 50 (quantity>=50) and 5% discount on quantity of bags purchased less than 50.
      • Write the following code in index.php file.
      • <html>
        <head>
        <title>If....else statement</title>
        </head>
        <body>
        <?php
        	//demonstration of code in if...else statement
        
        $quantity=50;
        $rate=150;
        
        	if($quantity>=50)
        	{
        		$discount=10;
        		echo "You get ".$discount."% discount<br>";
        		$discprice=$rate*($discount/100);
        		$rate-=$discprice;
        		$total=$quantity*$rate;
        		echo "Total bill = ".$total;
        	}
        	else
        	{
        		$discount=5;
        		echo "You get ".$discount."% discount<br>";
        		$discprice=$rate*($discount/100);
        		$rate-=$discprice;
        		$total=$quantity*$rate;
        		echo "Total bill = ".$total;
        	}
        
        ?>
        </body>
        </html>
        
      • We can write this code in the following manner also:
      • <html>
        <head>
        <title>If....else statement</title>
        </head>
        <body>
        <?php
        
        //another way of writing code
        $quantity=50;
        $rate=150;
        
        	if($quantity>=50)
        	{
        		$discount=10;
        	}
        	else
        	{
        		$discount=5;
        	}
        	
        	echo "You get ".$discount."% discount<br>";
        	$discprice=$rate*($discount/100);
        	$rate-=$discprice;
        	$total=$quantity*$rate;
        	echo "Total bill = ".$total;
        
        
        ?>
        </body>
        </html>
        
      • In the above example we decided the discount according to the quantity purchased.
      • Discount was calculated and deducted from the actual rate of the item.
      • Then the total bill was calculated.
      • In the above example we have rate as Rs. 150/- and quantity as 50. The output of it is shown below:
      • how_to_write_code_in_if_else_blocks
        fig 7

      • If you decrease the quantity, you will get 5% discount.

Thus we finished studying if…else statements with examples in this PHP if…else statements tutorial.

Previous articlePHP Operator’s
Next articlePHP Switch Statement

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -