basic loops in PHP

February 10, 2013

Loops execute a block of code a specified number of times, or while a specified condition is true.

for


for ($i = 1; $i <= 10; $i++) { echo $i . " × 12 = " . ($i * 12) . "
";
}

output:
1 × 12 = 12
2 × 12 = 24
3 × 12 = 36
. . .
10 × 12 = 120

An array created without specifying the index defaults to starting with 0, not 1:

$months = array("January", "February", "March", ... "December");
for ($i = 0; $i < 12; $i++) { echo $months[$i] . "
";
}

output:
January
February

December

count($array)

if the number of elements in the array can vary, use “count($array)” to find the number of (first level) elements each time:

for ($i = 0; $i < count($months); ++$i) { echo $months[$i] . '\n'; }

output:
January
February
...
December

foreach

However, alternately, if you don't know the array size, just say "foreach":

foreach ($months as $value) {
echo $value . "
";
}

output:
January
February
...
December

foreach ($months as $key => $mon) {
echo $key . " - " . $mon . "
";
}

output:
0 - January
1 - February
...
11 - December


$characters['pig'] = "Porky Pig";
$characters['duck'] = "Daffy Duck";
$characters['mouse'] = "Speedy Gonzales";

foreach ($characters as $key => $value) {
echo $value . " is a " . $key . ".
";
}

output:
Porky Pig is a pig.
Daffy Duck is a duck.
Speedy Gonzales is a mouse.

while


while (list($key, $value) = each($array)) {
echo "$key is $value \n";
}

$file = "employees.csv";
$employeeFile = fopen($file, "r");

while (!feof($employeeFile)) {
$data = fgets($employeeFile);
echo $data . "
";
}

# dump all the records into an array so that we can look ahead to the next record

$numrows = mysql_num_rows($result);
while ( $row = mysql_fetch_object($result) )
{
$rows[] = $row ;
}

for ($ii=1; $ii <= $numrows; ++$ii)

do until = do while

some languages use do until for a loop that always executes at least once. PHP simply puts the while at the end of the loop - so "while" achieves both needs.

example:

do {
$num = rand(1, $maxnum); ## A Random number between 1 and the maximum #
}
while ($num == $unwantednum) ;

 

 

Leave a Reply

We try to post all comments within 1 business day