0% found this document useful (0 votes)
249 views35 pages

PHP Control Flow Statements Explained

The document discusses various PHP control structures including conditional statements like if/elseif/else and switch statements, and repetitive structures like while, do-while, and for loops. Examples are provided to demonstrate how to use if/else, elseif, switch, while, do-while, for, break, continue, and other PHP control flow statements. The last section discusses a lab activity to create a PHP program that changes the background and text colors of a web page based on the day of the week using various control statements.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
249 views35 pages

PHP Control Flow Statements Explained

The document discusses various PHP control structures including conditional statements like if/elseif/else and switch statements, and repetitive structures like while, do-while, and for loops. Examples are provided to demonstrate how to use if/else, elseif, switch, while, do-while, for, break, continue, and other PHP control flow statements. The last section discusses a lab activity to create a PHP program that changes the background and text colors of a web page based on the day of the week using various control statements.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Web Programming

The PHP Control Statements


Conditional Structure Repetitive Structure

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Review on the Language Structure of PHP


How to start PHP? Creating and saving your PHP files PHP Delimeters Comments in PHP The use of Single and Double Quotations Variables (scalar and Constant Values Concatenation symbol !sca"e character and Casting #"erators ($%$&% &&% ''
Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

if statement
The if construct is one of the most im"ortant feature of many languages% including PHP( )t allows for conditional e*ecution of code fragments( PHP features an if structure that is similar to that of c
Syntax: if (expression/condition){ statement; }

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Example
<html> <head><title>Control Statements</title></head> <body> <?php $a !; $b "; if($a > $b) echo #a is bi$$er than b%; ?> </body> </html>
Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

!roup Several Statement


& <?php $a $b

!; "; if($a > $b) { echo #a is bi$$er than b%; $b $a;

} echo $b; ?> &


Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

What is "b#
& <?php $a !; $b "; if($a < $b) { echo #a is bi$$er than b%; $b $a; } echo $b; ?> &

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

What is "b#
& <?php $a !; $b "; if($a < $b) echo #a is bi$$er than b%; $b $a; echo $b; ?> &

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

What is "b#
& <?php $a !; $b "; if($a > $b) echo #a is bi$$er than b%; $b $a; echo $b; ?> &

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

else
else e*tends an if statement to e*ecute a statement in case the e*"ression in the if statement evaluates to '()S*(

& $a $b

!; "; if($a < $b) { echo #a is bi$$er than b%; } else { echo #b is smaller than a%;

}
FEU EAST ASIA COLLEGE

Information Technology Department

Web Programming

else if $ elseif
+s its name suggests% is a combination of if and else

& $a $b

!; "; if($a > $b) { echo #a is bi$$er than b%; } elseif($a < $b) { echo #a is smaller than b%; } else { echo #a and b are e+,al%;

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

% tric&' one

<?php $a -; $b !; if($a $b) { echo #.he expression is ./0*%; } else { echo #.he expression is '()S*%; } ?>
FEU EAST ASIA COLLEGE

Information Technology Department

Web Programming

%lternative S'ntax for if


)t is "ossible to write control statements using the following ,colon- format.
<?php $a !; if($a !)1 echo #( is e+,al to !%; endif; if($a -)1 echo #( is e+,al to -%; endif; ?>
Information Technology Department

FEU EAST ASIA COLLEGE

<?php $i -;

(ixing HT(L with PHP Control Statements


-) {

Web Programming

if ($i

?> <h2>.he condition is tr,e</h2> <center><b>$i is -</b></center> <?php } else { ?> <h2>.he condition is false</h2> <center><b>$i is not -</b></center> <?php } ?>
Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

switch statement
The switch statement controls "rogram flow by e*ecuting a s"ecific set of statements% de"ending on the value of an e*"ression( )t com"ares the value of an e*"ression to a value contained within a s"ecial statement called a case label( + case label in a switch statement re"resents a s"ecific value and contains one or more statements that e*ecute if the value of the case label matches the value of the switch statement/s e*"ression(
Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

switch statement
Synta*

s3itch (expression) { case label1 statement (s); brea4; case label1 statement(s); brea4; & defa,lt1 statement(s); }

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Example
<?php $n,m 2; s3itch ($n,m) { case -1 echo #.he 5$n,m is 6ne7; brea4; case 21 echo #.he 5$n,m is .3o7; brea4; case "1 echo #.he 5$n,m is .hree7; brea4; defa,lt1 echo 7(ny 8,mber7; } ?>
Information Technology Department

The $num is Two

FEU EAST ASIA COLLEGE

Web Programming

Example
<?php $n,m !; s3itch ($n,m 9 2) { case -1 echo #.he 5$n,m is 6ne7; brea4; case 21 echo #.he 5$n,m is .3o7; brea4; case "1 echo #.he 5$n,m is .hree7; brea4; defa,lt1 echo 7(ny 8,mber7; } ?>
Information Technology Department

The $num is One

FEU EAST ASIA COLLEGE

Web Programming

case Labels
case $*xample:ar1 statement(s); case #text strin$%1 statement(s); // ;ariable name // strin$ literal

case <!1 // inte$er literal statement(s); case =2<">?1 statement(s); // floatin$=point literal // conditional expression or operations

Case ($time < -@@)1 statement(s);


Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Repeating Code
while Statements
)t is one of the sim"lest ty"es of loo"s% which re"eats a statement or series of statements as long as a given conditional e*"ression evaluates to true( Synta*.

3hile (conditional expression) { statement(s); }

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Example

$Co,nt -; 2 3hile ($Co,nt < !) { 3 echo #$Co,nt <br />%; 4 AA$Co,nt; 5 } End of loop. echo #<p>*nd of loop></p>%;
Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Example

$Co,nt -@; 3hile ($Co,nt > @) { echo #$Co,nt <br />%; ==$Co,nt; } echo #<p>Be ha;e liftoff></p>%;
Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

)efine the output


$Co,nt -; 3hile ($Co,nt < -@@) { echo #$Co,nt <br />%; $Co,nt C 2; }

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

%lternative S'ntax
<?php $i -; -@)1 echo $i; $iAA; end3hile; ?> 3hile ($i <

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

do*while Statements
The do>>>3hile statement will always e*ecute the bloc0 of code once% it will then chec0 the condition% and re"eat the loo" while the condition is true( Syntax:

do { statement(s); } 3hile (conditional expression);

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Example

$Co,nt @; do { echo #.he co,nt is e+,al to $Co,nt<br/>%; AA$Co,nt; } 3hile ($Co,nt < 2);
Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

for statement
The for loop is used when you 0now in advance how many times the scri"t should run(

Synta*. for (counter declaration and initialization; condition; update statement) { statement(s); }
Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

The for loop


+ counting loo" is usually im"lemented with for
initiali3e chec0 for limit u"date loo" control inde* shorthand for i+i,-

for ($i @; $i < $co,nt; $iAA) { print(7<br>index ;al,e is 1 $i7); } one or more statements in the loo" body

Information Technology Department

FEU EAST ASIA COLLEGE

12

Web Programming

Example
<?php for ($Co,nt @; $Co,nt<-@; AA$Co,nt) { echo $Co,nt; } ?>

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

brea&
brea0 ends e*ecution of the current for% foreach% while% do4while or switch structure(
<?php for ($i @; $i < -@; AA$i) { if ($i !) brea4; print 7$i<br>7; } ?>

0 1 2 3 4

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Example
<?php for ($i - ; ; $iAA) { if ($i > -@) { brea4; } print $i; } ?>

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Example
<?php $i -; for (;;) { if ($i > -@) { brea4; } print $i; $iAA; } ?>
Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

continue
continue is used within loo"ing structures to s0i" the rest of the current loo" iteration and continue e*ecution at the condition evaluation and then the beginning of the ne*t iteration( <?php 0 for ($i @; $i < D; AA$i) { 1 if ($i ") 2 contin,e; 4 print 7$i<br>7; 5 } ?>
Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

print inside for statement


<?p p for (!i " 1; !i <" 1#; print !i$ !i%%); ?&

5rom this e*am"le% the print command was recogni3ed by the for function( )f ec o command will be used% the result will be error(

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Laborator' %ctivit'
Create a PHP "rogram that will ma0e use of a day in a wee0 to change the bac0ground color of your web "age as well as its te*t color( 6ou may use all the control statements discussed in PHP(

Information Technology Department

FEU EAST ASIA COLLEGE

Web Programming

Short .ui/ 0
1. What is $x, assuming that its initial value is 10 (3 pts) if($x>?) { if($x<E) $x @; } else $x -; 2. What is $x, assuming that its initial value is 10 (3 pts) if($x>?) { if ($x<E) $x @; else $x -; } 3. (4 pts ) $speed <!; $fee @>@; if ($speed > "!){ $fee 2@>@@; }elseif($speed > !@){ $fee ?@>@@; }elseif($speed > <!){ $fee D@>@@; } echo $fee;

Information Technology Department

FEU EAST ASIA COLLEGE

Common questions

Powered by AI

The outcome of the given PHP code is '20.00'. This occurs because the condition '$speed >= 35' evaluates to true, which assigns $fee the value of 20.00 and exits the if-elseif chain, preventing any further conditions from being evaluated, including '$speed >= 50' and '$speed >= 75', despite them also being true. The control flow of this chain respects only the first condition met within the structure .

A PHP script to change the webpage background color based on the day of the week can use switch statements by first determining the current day with date('l'), then using switch to map each day to a specific color. For example: ``` <?php $day = date('l'); switch ($day) { case 'Monday': $bgColor = 'lightblue'; break; case 'Tuesday': $bgColor = 'lightgreen'; break; // Additional cases for other days case 'Sunday': $bgColor = 'lightyellow'; break; default: $bgColor = 'white'; } echo "<style>body { background-color: $bgColor; }</style>"; ?> ``` This logic uses the switch statement to evaluate the current day against set values, assigns a corresponding color for each day, and applies it as a background style, demonstrating the effectiveness of switch for conditional logic based on a single variable .

In PHP, a do...while loop executes a block of code once before checking its condition at the end of the loop. This guarantees that the loop block will run at least once regardless of whether the condition is true or false. Conversely, a while loop evaluates its condition at the beginning of each iteration, which means that if the condition is false from the start, the loop block may not execute at all. This fundamental difference makes do...while useful when the initial execution of the loop block is necessary before any condition checks .

In PHP, the 'else if' construct, also known as 'elseif', allows the execution of conditional statements when an initial if expression evaluates to false but other conditions need checking. Unlike a simple if-else structure that checks only one condition, elseif provides a way to test multiple conditions in sequence. If the main if condition fails, the execution flows to the elseif condition before resorting to the final else block if all preceding conditions are false. This construct is particularly useful for complex decision trees where multiple conditions require evaluation in a tiered manner .

Using the echo command within the for function in PHP will result in an error because echo is a language construct, not a function, and cannot be used where functions are expected in certain contexts, such as within the part of a for loop where function calls are valid. In contrast, print is a valid function and can be used in the specific iterative section of the loop, which is why it works without error. This distinction highlights the syntactic role differences between echo and print within the PHP language .

In PHP, the 'continue' statement immediately ends the current iteration of a loop, skipping the remaining code block and proceeding directly to the next iteration. This can be useful in scenarios where certain elements should be omitted from processing without breaking out of the loop entirely, such as skipping invalid data or unnecessary calculations. Unlike 'break', which exits the loop altogether, 'continue' allows the loop to proceed with subsequent iterations, preserving the integrity of the loop structure for further processing. This is particularly suitable in filtering operations or when specific conditions dictate that processing should skip only particular items .

In PHP, single and double quotations are used differently for handling strings. Single-quoted strings are treated as literal text and are the simplest form. Variables within single quotes are not parsed or interpreted, which means that they appear as-is. Double-quoted strings, however, allow for variable interpolation, meaning PHP will parse the string to check for variables and replace them with their respective values. This makes double-quoted strings more flexible when you need to include variables but also slightly slower to process due to the additional parsing overhead .

The alternative syntax for PHP control structures uses a combination of colons and end markers like 'endif' or 'endforeach', enabling cleaner integration of PHP code within HTML without interfering with HTML layout. This format is particularly helpful for templating where repetitive or conditional sections of HTML need to be controlled by PHP logic. For example, using the if statement: <?php if($a == 5): ?> <p>A is equal to 5</p> <?php endif; ?> This keeps HTML tags separate and clean, improving readability as well as structure .

The switch statement in PHP operates by comparing the value of an expression against multiple case labels, executing the code block corresponding to the first matching case label. The syntax involves using the 'switch' keyword followed by an expression, then a series of 'case' labels and a 'default' label for handling unmatched cases. Compared to multiple if statements, a switch statement provides cleaner and more readable code, especially when checking a variable against many possible values. It also avoids repeated evaluations of the same expression, potentially offering better performance .

PHP handles conditional execution of code using the if statement, which allows for the execution of code fragments only when a specified condition evaluates to true. The syntax for implementing this structure in PHP is similar to C; it requires the condition to be placed within parentheses, followed by a code block enclosed in curly braces if the condition is true. For example, 'if (expression/condition){ statement; }'. This structure helps in creating dynamic and decision-based PHP applications .

You might also like