PHP Loops

PHP Loops

A loop is a language construct that allows you to execute a block of code more than once.

We are used to our scripts being executed in a linear fashion: from top to bottom, line by line, instruction by instruction. But what if you need to repeat some instruction several times?
For example, how do you display the natural numbers from 1 to 9? There is an obvious way:

This means that it is necessary to foresee in advance the situation when the true condition becomes false.

Now let's return to the task of displaying all natural numbers on the screen:

The ability to use loops and arrays together will immediately allow you to perform many interesting and varied tasks!

Earlier we already learned how to work with  arrays . For example, we can show all the values ​​of an array by referring to each of the elements by its index. But this is extremely tedious: accessing each of the array elements in turn, when we just want to show its entire value. Loops will get rid of this routine!

Using loops, you can display the contents of any array, and it only takes a few lines of code!

Let's rewrite the example with a list of favorite TV shows, but now using a loop:

Age: 27 
Occupation: Programmer

The original array, which should be shown as follows:

$user = [
    'name' => 'Lisa',
    'age' => '27',
    'Gender' => 'Female'

The script code that will bypass the array and show all of its contents will take only 4 lines:

foreach ($user as $key => $value) {
    print($key . ': ');
    print($value . '
); }

At each iteration of the loop, variables $keyand will be defined inside its body $value. The first will contain the next key of the array, and the second will contain the next value for this key.