techmore.in

PHP Control Statements

Control statements in PHP are essential for controlling the flow of execution within your scripts based on conditions, looping through code blocks, and making decisions. They help in writing dynamic and interactive PHP applications. Here’s an overview of the main types of control statements in PHP:

1. Conditional Statements

Conditional statements allow you to execute different blocks of code based on specified conditions.

if, else if, else

The if statement executes a block of code if a specified condition is true. Optionally, else if and else statements can be used to execute alternative blocks of code if the initial condition evaluates to false.

Example:

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

switch, case, break

The switch statement is used to perform different actions based on different conditions. It is often used as an alternative to multiple if statements.

Example:

php
<?php $day = "Monday"; switch ($day) { case "Monday": echo "Today is Monday."; break; case "Tuesday": echo "Today is Tuesday."; break; default: echo "It's neither Monday nor Tuesday."; } ?>

2. Looping Statements

Looping statements allow you to execute a block of code repeatedly.

for Loop

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

Example:

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

while Loop

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

Example:

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

do-while Loop

The do-while loop is similar to the while loop, except that it executes the block of code once before checking the condition.

Example:

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

foreach Loop

The foreach loop is used to iterate over arrays and objects.

Example:

php
<?php $colors = array("Red", "Green", "Blue"); foreach ($colors as $color) { echo "$color <br>"; } ?>

3. Jump Statements

Jump statements allow you to alter the normal flow of control within loops and switch statements.

break

The break statement terminates the current loop or switch statement and transfers control to the statement immediately following the terminated statement.

Example:

php
<?php for ($i = 1; $i <= 10; $i++) { if ($i == 6) { break; // Exit the loop when $i is 6 } echo "The number is: $i <br>"; } ?>

continue

The continue statement skips the rest of the current iteration of a loop and continues with the next iteration.

Example:

php
<?php for ($i = 1; $i <= 5; $i++) { if ($i == 3) { continue; // Skip iteration when $i is 3 } echo "The number is: $i <br>"; } ?>