Monday 2 February 2015

PHP Control Flow

PHP Control Flow

PHP if statement

if (expression) {
  statements;
}

if (expression) {
  statements;
} else {
  statements;
}

if (expression) {
  statements;
} elseif (expression) {
  statements;
} else {
  statements;
}
if (expression):
    statements;
elseif (expression):
    statements;
else:
    statements;
endif;

PHP while statement

while (expression) {
    statements;
}

do {
    statements;
} while (expression);
while (expression):
    statements;
endwhile;
PHP while with "each"
$a = array(1, 2, 3, 4);
while (list(, $value) = each($a)) {    # Iterate through each element of an array
    echo $value;
}

PHP for loop

for (initial_expr; condition_expr; increment_expr) {
    statements;
}
for (initial_expr; condition_expr; increment_expr):
    statements;
endfor;
Example
$a = array(1, 2, 3, 4);
for($i = 0; $i < sizeof($a); ++$i)
{
   echo $i;
}

PHP foreach loop

Looping the values of an array
foreach (array_expression as $value) {
    statements;                                   # Element is available as $value
}
Looping with key & value pair
foreach (array_expression as $key => $value) {
    statements;                                   # Key & element is available as $key & $value
}
Looping with key & value pair by reference
foreach ($a as &$value) {
    $value *= 2;                # in-place assignment
}

var_dump($a);                   # array(4) { [0]=> int(2) [1]=> int(4) [2]=> int(6) [3]=> ?(8) }
Example
$a = array(1, 2, 3, 4);

foreach ($a as $value) {
    echo $value;
}

PHP switch statement

switch (expression) {
    case value1:
        statements;
        break;
    case value2:
    case value3:
        statements;
        break;
    default:
        statements;
        break;
}

PHP Control Flow Statement

Flow controlDescription
breakbreak from the current loop or switch
continuecontinue to next iteration
Both break and continue take an optional value indicate where it break
while (...) {
    while (...) {
        while (...) {
            break 3;    // break 3 level - break out of the top most while loop
        }
    }
}

0 comments:

Post a Comment