The while loop in PHP. Syntax and array iteration. Code exam... open

The while loop in PHP. Syntax and array iteration. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

The while loop is only executed if the condition is true (as if( condition ) is tested). Obviously, with this way the loop works, its condition must change with each iteration, otherwise it will be an infinite loop. Let’s demonstrate the use of the loop in practice:

$names = ['John', 'Bratt', 'Homer']

$i = 0;//set the initial data for the body of the loop

while($i < count($names)) {
    echo "Name - $names[$i]";
    $i++;
}

If there is only one statement in the while block, then the curly braces of the block can be removed:

$counter = 0;
while(++$i<10)
    echo $i;

alternative syntax:

$i = 1;
while($i<10):
    echo $i;
    $i++;
endwhile;

Iterating the array using the for loop

list() – assigns values to variables from a list like an array
each() – returns the current element of the array, and then moves the pointer. (Do not support in PHP 8+)

//create array
$array[] = 1;
$array[] = 2;
$array[] = 3;
while(list(, $value) = each($array))
{
    echo $value . '<br>';

Iterating associative array using the while loop

$array['One'] = 1;
$array['Two'] = 2;
$array['Three'] = 3;

while(list($key, $value) = each($array))
{
    echo $key . '=&gt;' . $value . '<br>';	
}

do while loop

The do..while loop is similar to the while loop, only now the loop block is executed, and only then the condition is checked. That is, even if the condition is false, the loop block will be executed at least once:

$counter = 1;
do
{
    echo $counter * $counter . "<br />";
    $counter++;
}
while($counter<10)
A do-while loop is similar to a while loop, but it first executes a block of code and then checks a condition. Therefore, the code block will be executed at least once, even if the condition is initially false.
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation