PHP If Else - javatpoint
PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement in PHP.
PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true.
If statement is used to executes the block of code exist inside the if statement only if the specified condition is true.
Syntax
9.3M
169
Difference between JDK, JRE, and JVM
- if(condition){
- //code to be executed
- }
Flowchart
Example
- <?php
- $num=12;
- if($num<100){
- echo "$num is less than 100";
- }
- ?>
Output:
12 is less than 100
PHP If-else Statement
PHP if-else statement is executed whether condition is true or false.
If-else statement is slightly different from if statement. It executes one block of code if the specified condition is true and another block of code if the condition is false.
Syntax
- if(condition){
- //code to be executed if true
- }else{
- //code to be executed if false
- }
Flowchart
Example
- <?php
- $num=12;
- if($num%2==0){
- echo "$num is even number";
- }else{
- echo "$num is odd number";
- }
- ?>
Output:
12 is even number
PHP If-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can check multiple conditions using this statement.
Syntax
- if (condition1){
- //code to be executed if condition1 is true
- } elseif (condition2){
- //code to be executed if condition2 is true
- } elseif (condition3){
- //code to be executed if condition3 is true
- ....
- } else{
- //code to be executed if all given conditions are false
- }
Flowchart
Example
- <?php
- $marks=69;
- if ($marks<33){
- echo "fail";
- }
- else if ($marks>=34 && $marks<50) {
- echo "D grade";
- }
- else if ($marks>=50 && $marks<65) {
- echo "C grade";
- }
- else if ($marks>=65 && $marks<80) {
- echo "B grade";
- }
- else if ($marks>=80 && $marks<90) {
- echo "A grade";
- }
- else if ($marks>=90 && $marks<100) {
- echo "A+ grade";
- }
- else {
- echo "Invalid input";
- }
- ?>
Output:
B Grade
PHP nested if Statement
The nested if statement contains the if block inside another if block. The inner if statement executes only when specified condition in outer if statement is true.
Syntax
- if (condition) {
- //code to be executed if condition is true
- if (condition) {
- //code to be executed if condition is true
- }
- }
Flowchart
Example
- <?php
- $age = 23;
- $nationality = "Indian";
- //applying conditions on nationality and age
- if ($nationality == "Indian")
- {
- if ($age >= 18) {
- echo "Eligible to give vote";
- }
- else {
- echo "Not eligible to give vote";
- }
- }
- ?>
Output:
Eligible to give vote
PHP Switch Example
- <?php
- $a = 34; $b = 56; $c = 45;
- if ($a < $b) {
- if ($a < $c) {
- echo "$a is smaller than $b and $c";
- }
- }
- ?>
Output:
34 is smaller than 56 and 45