Chapter 1: - heikijapan/php-book2 GitHub Wiki
“I love coding. But coding isn't the thing I moved to Okinawa to do.”
These help control code execution flow: BREAK, CONTINUE, , RETURN, GOTO, EXIT and DIE.
BREAK -> breaks out from loops (eg foreach) by one level
CONTINUE -> if certain condition has been met then code will skip it
RETURN -> saves output of a function and then returns the value when ECHOED. RETURN also can the FLOW back to the main code flow
GOTO -> it 'flies' directly to the code where you have used named labels. It is a valid command in PHP but it makes code hard to follow therefore it's usages is discouraged.
EXIT and DIE -> they do the same thing Stops the script immediately. It can take strings as message die('No connection to DB'); therefor it can be used for debugging (cos script will stop there and the message gives you good info), but the message can also be info you want to display to users.
There are three types of LOOPS in PHP: FOR, FOREACH and WHILE loop.
Is the most commonly used loop and it is used heavily when working with ARRAYS and data structures.
<?php foreach ($names as $name) {
echo $name;
?>Use this type of loop when you know beforehand how many times the loop should run.
<?php for($i; $i <= 10; $i++) {
echo $i;
?>FOR loop can also be used like this:
// this will give <ul> with odd numbers, all even numbers will be skipped because using CONTINUE.
<ul>
<?php for ($i = 1; $i <= 10; $i++): ?>
<?php if($i % 2 == 0) continue; ?>
<li><?= $i ?></li>
<?php endfor; ?>
</ul>This is also a SUPER cool loop and is very often used when getting data from a database. This is also useful when reading files from a dir.
It is different from FOR and FOREACH loop cos it will be running all the time WHILE certain condition is TRUE.
<?php
$images_dir = __DIR__ . '/images';
$images_dir_handle = opendir($images_dir);
while (($my_image = readdir($images_dir_handle)) !== FALSE) {
echo $my_image;
}
?>