Raspberry Pi_Eng_24.4.6 Execution Control


Published Book on Amazon


All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 1
All of IOT Starting with the Latest Raspberry Pi from Beginner to Advanced – Volume 2


출판된 한글판 도서


최신 라즈베리파이(Raspberry Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (상)
최신 라즈베리파이(Raspberry Pi)로 시작하는 사물인터넷(IOT)의 모든 것 – 초보에서 고급까지 (하)


Original Book Contents


24.4.6  Execution Control

 

24.4.6.1    Conditional Control

 

The base value for determining "True" or "False" in the conditional expression is as follows.

    False           -- zero             

    True                      -- 1 or non zero

 

 

   if ... elseif ... else statement

 

"if" statement executes the specified command if the specified condition is "True", and checks the next new condition if "False". You can use a variant of "if ~" format, "if ~ else" format, and "if ~ elseif ~ else" format.

 

if  (condition) {
    code to be executed if condition is true;


} elseif (condition) {
    code to be executed if condition is true;   


} else {
    code to be executed if condition is false;  
}

 

[Used Example]

Next is an example of "if" statement.

 

<?php

 $t = date("H");

 

if ($t < "10") {

     echo "Have a good morning!";

 } elseif ($t < "20") {

     echo "Have a good day!";

 } else {

     echo "Have a good night!";

 }

 ?>

 

 

   switch statement

 

If the value of the expression matches the value of the specified condition, "switch" statement executes the specified statement until "break" statement is encountered. If there is no "break" statement, continue to process the following statement regardless of "case" statement. If the condition does not match, execute the statement specified in "default".

 

switch (n) {
    case value-1:
        code to be executed if n= value-1;
        break;
    case value-2:
        code to be executed if n= value-2;
        break;
    case value-3:
        code to be executed if n= value-3;
        break;
    default:
        code to be executed if n is different from all labels;
}

 

[Used Example]

Next is an example of "switch" statement.

 

<?php
$favcolor = "red";

switch ($favcolor) {
    case "red":
        echo "Your favorite color is red!";
        break;
    case "blue":
        echo "Your favorite color is blue!";
        break;
    case "green":
        echo "Your favorite color is green!";
        break;
    default:
        echo "Your favorite color is neither red, blue, or green!";
}
?>

 


 

24.4.6.2    Loop Processing

 

A loop processing can be used to repeatedly execute specific statements under a certain condition. The following loop processing can be used.

    while          -- Repeat processing while specified condition remains "True".

    do ... while -- Execute once first, and then repeat processing while specified condition remains "True".

    for            -- Repeat processing for the specified number of times.

    foreach       -- Iterate over each element in the array.

 

 

   "while" loop statement

 

"while" loop Repeats processing while certain conditions remain "True".

 

The following format can be used.

 

while (condition is true) {

    code to be executed;

 }

while (condition is true) :

    code to be executed;

endwhile

 

[Used Example]

Next is an example of "while" loop.

 

<?php
/* example 1 */

$i = 1;
while ($i <= 10) {
    echo $i++;  /* the printed value would be
                   $i before the increment
                   (post-increment) */
}

/* example 2 */

$i = 1;
while ($i <= 10):
    echo $i;
    $i++;
endwhile;
?>

 

 

   "do ... while" loop statement

 

"do while" loop executes the statement first once, then tests the condition and repeats processing while the specified condition remains "True".

 

do {
    code to be executed;
} while (condition is true);

 

You can see that because "do while" loop tests the specified condition after it first executes the specified statement, the statements will be executed at least once, even if the condition is "False" from the beginning.

 

[Used Example]

Here is an example of "do while" loop.

 

<?php
$x = 1;

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

 

 

   for loop statement

 

"for" loop executes the specified statement repeatedly the specified number of times.

 

for (init counter; test counter; increment counter) {

     code to be executed;

 }

for (expr1; expr2; expr3):

    statement

    ...

endfor;

 

    init counter             -- Initialize loop counter. This is starting value of loop counter.

    test counter            -- Specify the condition to repeat. The processing continues if it "True", and the processing ends if it is "False".

    increment counter    -- This is a way to increase the value of loop counter.

 

[Used Example]

Here is an example of "for" loop.

 

<?php
for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";
}
?>

 

 

   "foreach" loop statement

 

"foreach" loop can only be used in array. It repeats the specified statement for each element in the array.

 

When using only value in array, use the following format.

 

foreach (($array as $value) {

    statement

}

 

When using both key and value in array, use the following format.

 

foreach (($array as $key => $value) {

    statement

{

 

When iterating, the current element value of array is assigned to "$value", and the pointer of the array moves one by one. When the code is done for the last element of the array, the entire loop ends.

 

[Used Example]

The following is an example of using value only for array.

 

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
    echo "$value <br>";
}
?>

 

[Used Example]

The following is an example of using key and value for array at the same time.

 

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}
?>

 

 


 

24.4.6.3    Stopping and Continuing Loop Processing

 

   "break" statement

 

"break" statement terminates the currently executing loop processing in loop structure of "while", "do-while", "for", "foreach", and "switch", and proceeds to the command following the loop structure.

 

break  [ n ]

 

In the nested inner loop structure, "break" statement can use a numeric argument to specify to what level of upper loop structure to exit. Unless otherwise specified, a value "1" is assumed to be specified.

 

[Used Example]

Here is an example of "break" statement.

 

<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

/* Using the optional argument. */

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}
?>

 

 

   continue statement

 

In the loop structure, "continue" statement skips the remaining processing in a loop, goes to the step to evaluate the condition value, and continues the new iteration.

 

continue  [ n ]

 

In the nested inner loop structure, "continue " statement can use a numeric argument to specify to what level of upper loop structure to exit. Unless otherwise specified, a value "1" is assumed to be specified.

 

"break" and "continue" statement are differerent in that "break" statement stops processing and exit the specified loop structure, but "continue" omits the remaining processing to the specified loop structure and starts processing of the loop structure again.

 

[Used Example]

Here is an example of "continue" statement

 

<?php
while (list($key, $value) = each($arr)) {
    if (!($key % 2)) { // skip odd members
        continue;
    }
    do_something_odd($value);
}

$i = 0;
while ($i++ < 5) {
    echo "Outer<br />\n";
    while (1) {
        echo "Middle<br />\n";
        while (1) {
            echo "Inner<br />\n";
            continue 3;
        }
        echo "This never gets output.<br />\n";
    }
    echo "Neither does this.<br />\n";
}
?>