,

Control Structures in PHP: If, Elseif, Else, While, Do While, For Loop

Posted by


Introduction:

PHP control structures are used to control the flow of execution of a program. These structures include if-elseif-else statements, while and do-while loops, and for loops. In this tutorial, we will discuss each control structure in detail along with examples.

  1. If-Elseif-Else statement:

The if-elseif-else statement is used to execute a block of code based on a condition. The syntax of the if-elseif-else statement is as follows:

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

Example:

$age = 25;

if ($age < 18) {
   echo "You are a minor";
} elseif ($age >= 18 && $age < 65) {
   echo "You are an adult";
} else {
   echo "You are a senior";
}
  1. While loop:

The while loop is used to execute a block of code as long as the condition is true. The syntax of the while loop is as follows:

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

Example:

$count = 0;

while ($count < 5) {
   echo "Count is: $count";
   $count++;
}
  1. Do-While loop:

The do-while loop is similar to the while loop, but the code block is executed at least once even if the condition is false. The syntax of the do-while loop is as follows:

do {
   // code to be executed at least once
} while (condition);

Example:

$count = 0;

do {
   echo "Count is: $count";
   $count++;
} while ($count < 5);
  1. For loop:

The for loop is used to execute a block of code a specified number of times. The syntax of the for loop is as follows:

for (initialization; condition; increment/decrement) {
   // code to be executed in each iteration
}

Example:

for ($i = 0; $i < 5; $i++) {
   echo "Count is: $i";
}

Conclusion:

In this tutorial, we discussed the PHP control structures including if-elseif-else statements, while and do-while loops, and for loops. These control structures are essential for controlling the flow of execution in a PHP program. Practice using these control structures to improve your PHP programming skills.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x