PHP Index

In order to become familiar with PHP programming structures and commands, we will build various PHP pages.S Sections of this page will explain each PHP command, provide a link to a working sample, and detail the working sample's PHP code. Let's get started:



While Loops

While loops are very similar to if statements except the process code will run again and again (loop) while the condition evaluates to true. In addition, while loops are normally used when you do not know the number of iterations you must loop.

Here's some code:

$dollars = 15;
while ($dollars > 10)
{
echo "Hey, doll, I'm loaded with cash!";
echo "I have ".$dollars." dollars.
";
$dollars=$dollars-1;
}

The above code, like an if statement, evaluates the condition. If the
condition evaluates as true, the process code will run. Unlike an if statement, the process code will keep looping until the condition
evaluates as false.

Also notice that the condition is tested first and then the process code is run (if true). This is differerent than the Do While Loop.
Here's another example:whileloops.php

<html>
<head>
<title>whileloops.php</title>
</head>
<body>

<h1>John Luke's Lament</h1>
<p>He will be lonely until he has 10 friends...</p>

<?php

//set friendcount variable
$friendcount=0;

//start while loop with condition
while ($friendcount < 10)
{
//Time to be sad.
echo "Oh, I am so lonely. ";
echo "I have ".$friendcount." friends.<br><br>";

//add a friend!
$friendcount=$friendcount+1;
}

?>

</body>
</html>