minte9
LearnRemember



Switch

Evaluates the initial expression only once, then compares it against the values.
 
$a = 2;

switch($a) {

    case 1:
        echo 'one';
        break;

    case 2:
        echo 'two'; // two
        break;

    default:
}

Conditional

Conditional assigment operators are used to set a value depending on conditions.
 
/**
 * Conditional assigment operators
 * 
 * Ternary operator: 
 *      is a shorthand for the if ... else statement. 
 * 
 * Null coalescing: 
 *      is a shorthand for if does not exist or is NULL
 */

$a = 1;

echo $a == 1 ? 1 : 2;       // 1
echo !empty($b) ? $b : 2;   // 2
echo $b ?? 2;               // 2

While

With do / while the contents of the loop will be executed at least once.
 
/**
 * Even if the condition never evaluates to true ...
 * the content of the do / while is executed at least once.
 */

$i = 0;
$k = 0;

do {
    echo $i = $i + 1; // 1
} while ($i < 0); 

while ($k < 0) { 
    echo $k = $k + 1; // nothing
}

Break

It takes an optional parameter, which allows you to exit from multiple nested loops.
 
for ($i=0; $i<=10; $i++) {

    for ($j=0; $j<=10; $j++) {

        if ($j == 5) break 2; // Exist this loop and the next one
        
        echo $i; // 00000
    }
}



  Last update: 432 days ago