Learn Codeigniter

Control Structures In PHP

In PHP, there are two primary types of Control Structures.

  1. Branching
  2. Looping

Branching

There are 4 branching at PHP.they are given below.

If Statement

Syntax

if (Condition) {//write your code here }

Example

<?php
$age=19;
if ($age == 19) { 
echo "He is $age year old.";
} 
?>

Else Statement

Syntax

if (Condition) { // write your code here ,if the condition is TRUE } else { // write your code here ,if the condition is FALSE }

Example

<?php 
  if ($x > $y) {
   echo "x is bigger than y";
} else {
    echo "x is NOT bigger than y";
}
?>

Elseif Statement

Syntax

if (Condition) { // write your code here ,if the condition is TRUE } elseif (Another Condition) { // write your code here ,if the condition is FALSE } else { // write your code here ,In all other cases }

Example

<?php 
$x=1;
if ($x==2) {
echo  "$x is equal to 2";
} else if ($x == 1) {
echo  "$x is equal to 1";
} else {
   echo "$x does not equal 2 or 1";
}
?>

Switch Statement

Syntax

switch($n){ case result1: // write your code here, if expression results in result1 ; break; case result2: // write your code here, if expression results in result2 ; break; default: // write your code here, if expression results in result3 ; break; }

Example

<?php 
switch ($i) {
    case 0:
       echo "i equals 0";
    case 1:
        echo "i equals 1";
    case 2:
        echo "i equals 2";
}
?>

Looping

While Statement

Syntax

while (Condition) { // write your code here }

Example

<?php 
$i=4;
while ($i <= 10) {
echo $i;  
$i++;
?>

Do.. While Statement

Syntax

do { // write your code here } while (Condition);

Example

<?php 
$num = 1;
do {
echo "Execution number: $num";
$num++;
} while ($num >10); 
?>

For Statement

Syntax

for (initialization expr1;test expr2; modification expr3 ) { // write your code here}

Example

<?php 
for ($i = 1; $i <= 10; $i++) {
    echo $i;
}
?>