Search
Close this search box.
Search
Close this search box.

Loops

For loop

The for loop is used when you know in advance how many times the script should run.

$nItems = count($myArray);
for ($i = 0; $i < $nItems; $i += 1)
{
     // do something with $i
     echo $myArray[$i];
}

For each loop

The foreach loop is used to loop through arrays.

// keys and values
foreach ($array as $key => $value) {
    echo $key;
    echo $value;
}

// just the values
foreach ($array as $value)
{
    echo $value;
}