PHP Loops & Conditions

PHP Loops & Conditions

Using Loops and Conditions in PHP


PHP Conditional Statements


Conditional statements in PHP allow you to execute different blocks of code based on specified conditions. The most commonly used conditional statements are if, else, elseif, and switch.


if Statement: The if statement executes a block of code if a specified condition is true.

<?php
$age = 25;
if ($age >= 18) {
echo “You are an adult.”;
}
?>


else Statement: The else statement executes a block of code if the if condition is false.


<?php
$age = 15;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>


elseif Statement: The elseif statement allows you to specify multiple conditions to test.

<?php
$grade = 'B';
if ($grade == 'A') {
echo "Excellent!";
} elseif ($grade == 'B') {
echo "Good job!";
} else {
echo "Work harder!";
}
?>



switch Statement: The switch statement is used to perform different actions based on different conditions.

<?php
$color = 'red';
switch ($color) {
case 'red':
echo "Your favorite color is red!";
break;
case 'blue':
echo "Your favorite color is blue!";
break;
default:
echo "Your favorite color is neither red nor blue.";
}
?>



PHP Loop Structures


Loops in PHP are used to execute a block of code repeatedly based on a condition. The most commonly used loop structures are for, while, do-while, and foreach.


for Loop: The for loop executes a block of code a specified number of times.


<?php
for ($i = 1; $i <= 5; $i++) {
echo "The value of i is: $i <br>";
}
?>


while Loop: The while loop executes a block of code as long as a specified condition is true.


<?php
$i = 1;
while ($i <= 5) {
echo "The value of i is: $i <br>";
$i++;
}
?>


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


<?php
$i = 1;
do {
echo "The value of i is: $i <br>";
$i++;
} while ($i <= 5);
?>


foreach Loop: The foreach loop is used to loop through arrays.


<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo "$color <br>";
}
?>




Learning Resources



PHP Manual – Control Structures: Refer to the official PHP documentation for detailed explanations and examples of loops and conditional statements.
W3Schools PHP Tutorial: Explore interactive tutorials and examples to learn PHP programming concepts.

Leave a Comment

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

Scroll to Top