Understanding Conditional Statements in PHP

Conditional Statements PHP

Conditional statements in PHP play a crucial role when you need to execute a set of operations based on specific conditions. The IF family, including IF, IF-ELSE, IF-ELSE-IF, Nested IFs, and Switch, offers a variety of ways to control the flow of your program based on the evaluation of conditions.

1. IF Statement

Syntax

if(conditional-expression)
{
  //code
}

Example

<?php
$x = 30;
$y = 30;
if ($x == $y) {
  echo("x and y are equal");
}
?>

Output: `x and y are equal`

2. IF-ELSE Statement

Syntax

if(conditional-expression)
{
  //code
} else {
  //code
}

Example

<?php
$x = 30;
$y = 60;
if ($x == $y) {
  echo("x and y are equal");
} else {
  echo("x and y are not equal");
}
?>

Output: `x and y are not equal`

3. IF-ELSE-IF Ladder

Syntax

if(conditional-expression-1)
{
  //code
} else if(conditional-expression-2) {
  //code
} else if(conditional-expression-3) {
  //code
}
//...
else {
  //code
}

Example

<?php
$age = 15;
if ($age <= 1 && $age >= 0) {
  echo("Infant");
} else if ($age > 1 && $age <= 3) {
  echo("Toddler");
} else if ($age > 3 && $age <= 9) {
  echo("Child");
} else if ($age > 9 && $age <= 18) {
  echo("Teen");
} else if ($age > 18) {
  echo("Adult");
} else {
  echo("Invalid age");
}
?>

Output: `Teen`

4. Nested IF

Syntax

if(conditional-expression-1) {
//code
  if(conditional-expression-2) {
  //code
    if(conditional-expression-3) {
    //code
    }
  }
}

Example

<?php
$age = 50;
$resident = "yes";
if ($age > 18)
{
  if($resident == "yes"){
    echo("Eligible to Vote");
  }
}
?>

Output: `Eligible to Vote`

5. Switch Statement

Syntax

switch(conditional-expression){
case value1:
//code
break; //optional
case value2:
//code
break; //optional
//...
default:
//code to be executed when all the above cases are not matched;
}

Example

<?php
$day = 3;
switch($day){
case 1: echo("Sunday");
break;
case 2: echo("Monday");
break;
case 3: echo("Tuesday");
break;
case 4: echo("Wednesday");
break;
case 5: echo("Thursday");
break;
case 6: echo("Friday");
break;
case 7: echo("Saturday");
break;
default:echo("Invalid day");
break;
}
?>

Output: `Tuesday`

Understanding and mastering these conditional statements will empower you to create more dynamic and responsive PHP applications. Each type serves a specific purpose, and choosing the right one for a particular scenario ensures efficient and maintainable code.

You may also like:

Related Posts

Leave a Reply