Tuesday, May 3, 2016

WDP - Selection Structure & PHP Loop

Explain the purpose of each statement, identify the syntax, and give example  codes and the output.


SELECTION STRUCTURE 

  • if statement

executes some code if one condition is true, which performs a function or displays information. Below is a general example of an if statement, not specific to any particular programming language.
if (X < 10) {
     print "Hello John";
}   
In the example above, if the value of X were equal to any number less than 10, the program would print or display, "Hello John".
  • if ...else statement
 executes some code if a condition is true and another code if that condition is false

<?php

$a = 20;

if ($a < 50) {
    echo "Have a good day!";
else {
    echo "Have a good night!";
}
?>


  • if ...elseif ...else statement
executes different codes for more than two conditions

<?php

$a = age;

if ($a < 18) {
    echo "Hello youngster!";
elseif ($a < 40) {
    echo "Hello elder!";
else {
    echo "Hello old folks!";
}

?>


  • switch statement
selects one of many blocks of code to be executed

<?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, nor green!";
}
?>



PHP LOOPS

  • while statement
loops through a block of code as long as the specified condition is true

<?php 
$x = 1; 

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

?>

  • do ...while statement
 loops through a block of code once, and then repeats the loop as long as the specified condition is true

<?php 
$x = 2; 

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



Result :

The number is 2
The number is 3
The number is 4
The number is 5


  • for statement
loops through a block of code a specified number of times

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

?>
  • foreach statement
loops through a block of code for each element in an array

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

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


reference : 


No comments:

Post a Comment