Task Seven - While Loop - PHP Tutorial
This is the first program in this tutorial that carries out multiple tasks.
It repeats until you type a zero to end the program. It expects you to
enter a number and it prints a row of '*' characters where the length
of the row is controlled by the number you enter. This program structure
enables programs with a menu to be written. This program uses a "while"
loop. There is more information about "while"loops here.
Here is the result of running the program.

Here is the program code.
<?php
// -----------------------------------------------------------------
// ----- This function returns a string consisting of $theChar -----
// ----- repeated $repCount times. -----
// -----------------------------------------------------------------
function repchar($theChar, $repCount)
{
$s = "";
for ($ii = 0; $ii < $repCount; $ii++)
{
$s = $s . $theChar;
}
return $s;
}
// -----------------------------------------------------------------
$run = True;
while ($run)
{
echo "Enter a whole number (0 to quit) ... ";
$num = fgets(STDIN);
if ($num == 0)
{
$run = False;
}
else
{
echo(repchar("*", $num))."\n";
}
}
// -----------------------------------------------------------------
?>
|
Code |
Explanation |
$run = True; |
This is a Boolean. It is used to control the repetition of the while
loop. As long as $run is true, the loop will keep repeating. |
while ($run)
{
// This block of code is repeated
// as long as $run is true.
}
|
This is the structure of the while loop. The block of code inside the
curly brackets is repeated as long as the Boolean, ($run) in this case,
is true. |
Learning Task
Write a program using a while loop and an IF statement to act as a menu. The
menu choices should be
- Press i or I to Insert
- Press e or E Edit
- Press d or D Delete
- Press q or Q Quit
Write three functions named, insert, edit and delete. These are stub
functions. They will not actually work but they act as place holders so you
can set up the program structure. The functions should echo text to show they
are present and working. Suitable text would be Insert, Edit and Delete.
|