Control Structures: Conditional Statements

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Control Structures

Conditional Statements

if() Statement

<?php <?php
if(conditional test) if($temp >=100)
{ {
//do this. echo ‘Very hot!!!’;
} }
?> ?>

if-else() Statement

<?php <?php
if(conditional test) if($temp>=100)
{ {
//do this echo ‘Very hot!!!’;
} }
else else
{ {
//do this echo ‘Within tolerable limits.’;
} }
?> ?>

if-elseif-else() Statement

<?php <?php
if(conditional test #1) if($country == ’UK’ )
{ {
//do this $capital = ‘London’;
} }
elseif(conditional test #2) elseif($country == ‘US’)
{ {
//do this $capital = ‘Washington’;
} }
else else
{ {
//do this $capital = ‘Unknown’;
} }
?> ?>

switch() Statement

<?php <?php
switch(condition variable) switch($country)
{ {
case possible result #1: case ‘UK’:
//do this $capital = ‘London’;
case possible result #2: break;
//do this case ‘US’:
case default: $capital = ‘Washington’;
//do this break;
} default:
?> $capital = ‘Unknown’;
break;
}
?>

Ternary Operator – provides a short-cut syntax for if-else statement.

<?php
$msg = $dialCount > 10 ? ‘Cannot connect after 10 attempts.’ : ‘Dialing’;
?>

Loops

while() Loop

<?php <?php
while(condition is true) $num = 11;
{ $upperLimit = 10;
//do this $lowerLimit = 1;
} while($lowerLimit <= $upperLimit)
?> {
echo “$num x $lowerLimit = ”. ($num * $lowerLimit) .”<br>”;
$lowerLimit++;
}
?>
do() Loop

<?php <?php
do $num = 11;
{ $upperLimit = 10;
//do this $lowerLimit = 1;
}while (condition is true) do
?> {
echo “$num x $lowerLimit = ”. ($num * $lowerLimit) . “<br>”;
lowerLimit++;
}while ($lowerLimit<=$upperLimit)
?>

for() Loop

<?php <?php
for(initialize counter; conditional test; update counter) for($x = 2; $x <= 100; $x++)
{ {
//do this echo “$x ”;
} }
?> ?>

Controlling Loop Iteration with Break and Continue

The break keyword is used to exit a loop whenever it encounters an unexpected situation. The continue keyword is used
to skip a particular iteration of a loop and move to the next iteration immediately.

<?php <?php
for($x = -10; $x <= 10; $x++) for($x = 10; $x<=100; $x++)
{ {
if($x == 0) { break; } if(($x%2)==0)
echo ‘100/’. $x .’ = ’.(100/$x); {
} echo “$x ”;
?> }
else
{
continue;
}
}
?>

You might also like