PHP Decision Making

please click here for more wordpress cource

In PHP, decision making is done using conditional statements. The following are the conditional statements available in PHP:

  1. if statement:

The if statement is used to check if a condition is true or false. If the condition is true, the code inside the if statement will be executed.

Syntax:

if (condition) {
   // code to be executed if the condition is true
}

Example:

$num = 10;

if ($num > 5) {
    echo "The number is greater than 5";
}
  1. if-else statement:

The if-else statement is used when you want to execute one block of code if a condition is true, and another block of code if the condition is false.

Syntax:

if (condition) {
   // code to be executed if the condition is true
} else {
   // code to be executed if the condition is false
}

Example:

$num = 10;

if ($num > 20) {
    echo "The number is greater than 20";
} else {
    echo "The number is less than or equal to 20";
}
  1. if-else-if statement:

The if-else-if statement is used when you have multiple conditions to check. It allows you to check each condition one by one until a condition is true.

Syntax:

if (condition1) {
   // code to be executed if condition1 is true
} else if (condition2) {
   // code to be executed if condition2 is true
} else {
   // code to be executed if all conditions are false
}

Example:

$num = 10;

if ($num > 20) {
    echo "The number is greater than 20";
} else if ($num > 5) {
    echo "The number is greater than 5 but less than or equal to 20";
} else {
    echo "The number is less than or equal to 5";
}
  1. switch statement:

The switch statement is used when you have multiple cases to check. It allows you to execute different blocks of code based on different values of a variable.

Syntax:

switch (variable) {
    case value1:
        // code to be executed if variable is equal to value1
        break;
    case value2:
        // code to be executed if variable is equal to value2
        break;
    .
    .
    .
    default:
        // code to be executed if variable is not equal to any of the values
}

Example:

$num = 3;

switch ($num) {
    case 1:
        echo "The number is 1";
        break;
    case 2:
        echo "The number is 2";
        break;
    case 3:
        echo "The number is 3";
        break;
    default:
        echo "The number is not 1, 2, or 3";
}

You may also like...

Popular Posts

Leave a Reply

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