Science Library - free educational site

Loops and Conditionals (PHP)

Loops with PHP

Computers are really good at repetitive tasks. When a task is repeated, a loop is made and the programme set to repeat the tasks within the loop until it fulfills some limits set. These can be a number of loop cycles, using a counter. Or it could be a condition: e.g. 'keep adding numbers until the total is greater than or equal to 100'. At the conclusion of the count or when the condition is met, the programme exits the loop and continues with the script that follows.

There are different ways to make loops, depending on the application in question:

For loop

for (initial expression; condition; closing expression) {

//code that repeats till the condition is no longer true


for loops often use a counter, so that the loop executes a precise number of times.

echo '<select name="year">';

for ($year = 2000; $year <= 2020; $year++) {

echo "<option value=\"$year\">$year</option>\n";


echo '</select>';

This code creates a dropdown select menu with the options the years 2000-2020, inclusive.

While loop

while (condition) {

//code that repeats while the condition is true


Black Hole
Black Hole: "...from whose bourn no traveller returns" - the fate of programmes that stray unawares into an infinite loop

As opposed to for loops, while loops are not limited to a set number of iterations, instead will remain (potentially infinitely) looping till a set condition is no longer true. Care must therefore be taken not to create an infinite loop - one that cannot be fulfilled, so the programme enters a loop and never exits, in a sort of black hole logic trap.

// example of an infinite loop*

while (1 < 2) {

echo 'Hey! Who turned out the lights!';


// * do not try this at home

The while loop will not execute if the condition is never true. while loops are used to retrieve data from a database, particularly when it is not known how many records there are.

echo 'while($row = mysqli_fetch_array($r)) {';

// execute some code using the dbase records one at a time


This code comes after a Mysql query has returned a set of records from a database. It takes each record in turn from the returned array, assigns it the variable $row, and executes some code.


if ... else

When a logic chain is developed in PHP or JavaScript, conditions are set to guide the response of the programmes.

For example, depending on the gender of the visitor, a printout chooses between the 'Dear Sir' salutation, rather than 'Dear Madam'. The programme simply states: "If visitor is male, print 'Dear Sir', if not 'Dear Madam'."

In PHP the syntax is:

if ($gender = 'Male') {
echo 'Dear Sir';
} else {
echo 'Dear Madam';

A logic chain could have more than two possible conditions, and can check them in sequence with an 'elseif' clause:

if ($gender = 'Male') {
echo 'Dear Sir';
} elseif ($gender = 'Female') {
echo 'Dear Madam';
} else {
echo 'You have not selected a gender!';

Logical operators

&&and\$var1 && $var2
||or\$var1 || $var2
XORand not\$var1 XOR $var2

Comparative operators

==is equal to$var1 == 42
!=is not equal to$var1 != 42
<less than$var1 < 42
>greater than$var1 > 42
<=less than or equal to\$var1 <= $var2
>=greater than or equal to\$var1 >= $var2
Check if a value has been input

\$variable1 is true if \$variable1 has value that is not: 0, an empty string, FALSE or NULL.

isset(\$variable1) is a function that checks the \$variable1 has a value that is not NULL. NB. if the value in \$variable1 is 0, an empty string, FALSE, the isset function will return true. NULL means no set value.

isset() is useful for checking if an input has been made to a field in a form, which may or may not be necessary. If the field has been left by the user, then isset() will return false, and a different action can be set. For example, no input may invalidate the form (for mandatory fields, such as name), or a default value can be set (such as an existing $user_name, imported for this user from some other page on the site).

if (isset(\$_REQUEST['$name']) {
\$user = $_REQUEST['$name'];
echo 'Dear ' .$user;
} elseif ($user) {
echo 'Dear' .$user;
} else {
echo 'You have not entered your name!';


if-elseif-else conditional clauses are in theory unlimited in length. However, they can get confusing and cause errors. As a substitute, PHP provides a conditional which 'switches' through a series of possible values for a variable, and executes the following code if there is a match. If no match is found in the list, an optional default code is executed.

switch($variable) {
case 'value1':
\\ execute this code
case 'value2':
\\ execute this different code
case 'value3':
\\ execute this different code
\\ execute this code if there is no match (optional)

Validating Forms

The function isset() returns true for the empty field ''. This means it cannot be used to check that a form input field has been completed correctly.

The function empty(), on the other hand, checks to make sure there is a string in the variable returned from a field submitted by a form, and not '', 0, NULL, or FALSE.

if (!empty(\$_REQUEST['$name']) {
\$user = \$_REQUEST['$name'];
} else {
echo '<p class="error">You have not entered your name!';

Content © Renewable.Media. All rights reserved. Created : August 12, 2014 Last updated :February 14, 2016

Latest Item on Science Library:

The most recent article is:


View this item in the topic:

Vectors and Trigonometry

and many more articles in the subject:

Subject of the Week


Information Technology, Computer Science, website design, database management, robotics, new technology, internet and much more. JavaScript, PHP, HTML, CSS, Python, ... Have fun while learning to make your own websites with

Computer Science

Great Scientists

Jakob Bernoulli

1654 - 1705

Jakob Bernoulli was the first of long series of Bernoulli family members, all mathematicians, whose combined contributions to mathematics and physics is unequalled in history.

Jakob Bernouilli, 1654 - 1705, Swiss mathematician
IT Forum by Sean Bone

Quote of the day...

You cannot solve a problem using the same sort of thinking that caused the problem in the first place.

Renewable.Media Internet Promotions

English language school