The for loop in PHP. Syntax and array iteration. Code exampl... open

The for 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 for loop has the following formal definition:

for ([counter initialization]; [condition]; [counter change])
{
     // actions
}

example for loop:

for ($i = 1; $i < 10; $i++)
{
    echo $i;
}

Parts of the for loop declaration may be missing. For example, there is no counter definition (it can be defined outside the loop):

$m = 5;
for (; $m < 10; $m++)
{
    echo $m;
}

Changing the counter value and change it inside the loop:

$i = 0;
for (; $i < 10;)
{
    echo $i;
    $i += 2;
}

Also, you can define and use several variables in the loop declaration at once:

for ($i =1, $m=1; $i + $m < 100; $i++, $j+=10)
{
    echo "$i + $m = " . $i + $m ";
}

alternative syntax:

for ($i = 1; $i < 10; $i++):
    echo  $i * $i";
endfor;

Iterating the array using the for loop

//create array
$array[] = '1';
$array[] = '2';
$array[] = '3';

//count array length
$count = count($array);

//pass the array
for ($i=0; $i<$count; $i++)
{
    echo $array[$i];	
}

Pass associative array using the for loop

reset() – sets the pointer to the first element of the array;

next() – moves the pointer forward one element of the array;

key() – returns the key of the current array element.

$array['One'] = 1;
$array['Two'] = 2;
$array['Three'] = 3;
for (reset($array); ($key = key($array)); next($array))
{
    echo $key. '=&gt;' .$array[$key] . '<br>';	
}
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