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.

Conditionals

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:

<?php
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:

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

Logical operators

SymbolOperationExample
!not!empty
&&and\$var1 && $var2
||or\$var1 || $var2
XORand not\$var1 XOR $var2

Comparative operators

SymbolOperationExample
==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).

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

Switch

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.

<?php
switch($variable) {
case 'value1':
\\ execute this code
break;
case 'value2':
\\ execute this different code
break;
case 'value3':
\\ execute this different code
break;
default:
\\ execute this code if there is no match (optional)
break;
}
?>

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.

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

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

Latest Item on Science Library:

The most recent article is:

Fission

View this item in the topic:

Nuclear and Particle Physics

and many more articles in the subject:

Subject of the Week

Physics

Physics is the science of the very small and the very large. Learn about Isaac Newton, who gave us the laws of motion and optics, and Albert Einstein, who explained the relativity of all things, as well as catch up on all the latest news about Physics, on ScienceLibrary.info.

Gravity lens

Great Scientists

Niels Bohr

1885 - 1962

Niels Bohr, 1885 - 1962, was a Danish physicist, and founder of the Copenhagen School, which proposes as a consequence of quantum mechanics that there is no fundamental reality, a view much opposed by Albert Einstein.

Niels Bohr, 1885 - 1962. A Danish physicist
IT Forum by Sean Bone

Quote of the day...

Read, read, read, read, read, read... if you do not read, you will never make a great film.

ZumGuy Internet Promotions

Renewable energy media services