top of page

PHP: Control instructions

  • Writer: Ameni OUERTANI
    Ameni OUERTANI
  • Nov 21, 2018
  • 11 min read

Most of the script control statements are found in PHP. Indispensable to

the management of the progress of any algorithm, these instructions are present

in all languages. PHP uses a syntax very similar to that of the C language.

ree


Conditional instructions

Like any language, PHP has conditional statements that allow

to direct the progress of a script according to the value of data.


The if statement

The if statement is the simplest and most used of the conditional statements.

Present in all programming languages, it is essential because it allows to direct the execution of the script according to the Boolean value of an

expression.


Its syntax is as follows:

if (expression) statement;

If the expression included in the parentheses is evaluated to the Boolean value TRUE,

the following statement is executed. Otherwise, the execution goes directly to

the next line.

The if statement can be followed by an instruction block delimited by parentheses

which will be fully executed under the same conditions:

if (expression)
{
// block of code
}

Writing the phrase is important. It can become complex when it

includes logical operators associating its different components.


In the following code:

<? Php
$ A = 6;
if (is_integer ($ a) && ($ a <10 && $ a> 5) && ($ a% 2 == 0)) {
echo "Conditions satisfied";
}
?>

the compound expression

(is_integer ($ a) && ($ a <10 && $ a> 5) && ($ a% 2 == 0))

is valued at TRUE if $ a simultaneously meets the following three conditions: be an

integer, be between 5 and 10 and be divisible by 2, for $ a the values possible are 6 and 8 only.

The message is only displayed in these cases.

PHP performs a Boolean evaluation of a large number of expressions that do not

contain in themselves Boolean variables. It admits, for example,

expressions like:

$ a = 25;
if ($ a) {
echo "The condition is true <br />";
}

In this case, it is not the value of the variable $ a which is taken into account but its

Boolean rating, which is TRUE.


The if ... else statement

The if ... else statement handles the case where the conditional expression is true

and at the same time write a spare treatment when it is evaluated at FALSE, this

does not allow an if statement alone. The statement or block that follows else is then

the only one to be executed. The execution then continues normally after the else block.

the following example calculates the net price after a variable discount depending on the amount of purchases according to the following criteria:


  • If the total price is more than 100 euros, the discount is 10%. This condition is handled by the if statement.

  • For amounts less than or equal to 100 euros, the discount is 5%. This condition is handled by the else statement.


Example of the if ... else statement:

<? Php
$ price = 55;
if ($ price> 100) ←
{
echo "<b> For a purchase amount of $ price & euro ;, discount is 10% </ b>
<br /> ";
echo "The net price is", $ price * 0.90;
}
else ←
{
echo "<b> For a purchase amount of $ price & euro ;, the discount is 5% </ b> <br />";
echo "<h3> The net price is", $ price * 0.95, "</ h3>";
}
?>

Given the value assigned here to the variable $ a, the script displays the result

following :

For a purchase amount of 55 ¤, the discount is 5%
The net price is 52.25 ¤

The block following the if or else statements can contain all sorts of instructions, including other if ... else statements.

We obtain in this case a syntax more complex, of the form:

if (expression1)
{// Block 1}
elseif (expression2)
{// Block 2}
else
{// Block 3}

This construction is interpreted as follows: if the expression 1 is evaluated to TRUE,

block 1 is executed; otherwise, if the expression 2 following the elseif statement

is evaluated to TRUE, block 2 is executed. In other cases, block 3 is

executed.

Whatever the situation, only one block is executed.


In the next example, you want to display the amount of a discount calculated according to the following conditions:

  • If you buy a PC over 1000 euros, the discount is 15%.

  • For a PC of 1000 euros or less, the discount is 10%.

  • For books, the discount is 5%.

  • For all other items, the discount is 2%.

The first statement if ... elseif ... else controls the category of the

product. The second if ... else statement determines the discount amount. Code indentation makes reading easier.


Nested if statements

<? Php
// ******************** if ... elseif ... else ****************
$ Cat = "PC";
$ Price = 900;
if ($ cat == "PC") ←
{
if ($ price> = 1000) ←
{
echo "<b> For the purchase of a PC in the amount of $ price & euro ;, the discount is 15% </ b> <br /> ";
echo "<h3> The net price is:", $ price * 0.85, "& euro; </h3>";
}
else ←
{
echo "<b> For the purchase of a PC in the amount of $ price & euro ;, the discount is 10% </ b> <br /> ";
echo "<h3> The net price is:", $ price * 0.90, "& euro; </h3>";
}
}
elseif ($ cat == "Books") ←
{
echo "<b> For the purchase of books the discount is 5% </ b> <br />";
echo "<h3> The net price is:", $ price * 0.95, "& euro; </ h3>";
}
else ←
{
echo "<b> For other purchases the discount is 2% </ b> <br />";
echo "<h3> The net price is:", $ price * 0.98, "& euro; </ h3>";
}
?>

The result of this script for $ cat at the value "PC" and the variable $ price at the value 900 gives the following display:

For the purchase of a PC for 900 €, the discount is 10%
The net price is: 810 €

The operators ? and ??


The operator ? can advantageously replace an if ... else statement in

evaluating an expression and assigning a variable a first value if the

condition is true or another value if it is false.

Its syntax is as follows:

$ var = expression? value1: value2
It is equivalent to:
if (expression) {$ var = value1;}
else {$ var = value2;}

The first example of discount calculation could be written:

$ var = ($ price> 100)? "the discount is 10%": "the discount is 5%";
echo "<b> For a purchase amount of $ price & euro ;: $ var </ b> <br />";
instead of :
if ($ price> 100)
{
echo "<b> For a purchase amount of $ price & euro ;, the discount is 10% </ b> <br />";
}
else
{
echo "<b> For a purchase amount of $ price & euro ;, the discount is 5% </ b> <br />";
}

This operator is usually used with short Boolean expressions.


the following example fits a text according to the value of a variable, either for a

polite formula depending on the sex of the visitor, either to put a word in the plural

according to a number.


The operator ?

<? Php
$ ch = "Hello";
$ Gender = 'M';
$ ch = ($ sex == "F")? "Madam": "Sir";
echo "<h2> $ ch </ h2>";
$ nb = 3;
$ pmu = "We have to find". $ nb;
$ word = ($ nb == 1)? "horse": "horses";
echo "<h3> $ pmu $ word </ h3>";
?>

Given the values ​​of the variables $ sex and $ nb the result returned is the following:

Hello sir
We have to find 3 horses

In addition to the previous operator, PHP 7 adds the operator ?? which returns the

value of the first operand if it exists and if it does not have the value NULL or that of the second operand otherwise.

Its syntax is:

$ var = $ value1 ?? $ value2;

Note that the second operand can be a string and be the default value.

This code is equivalent to:

$ var = isset ($ value1)? $ value1: $ value2;

We can also chain this operator several times in the form:

$ var = $ value1 ?? $ value2 ?? $ value3;

The assignment being made in this case with the first existing variable and not null.


A typical use is the management of entries in a form, because it can retrieve the value of a field or assign it a default valuen. In the example below:

$ name = $ _ POST ['name'] ?? 'Anonymous';

if the user enters his name in the form field named 'name', the variable $ name

will contain it, otherwise it will have the value 'Anonymous'.


The switch ... case statement


Supposedly, you want to associate a department code with its real name. With

a sequence of if statements, you would write the following script:

<? Php
$ dept = 75;
if ($ dept == 75) echo "Paris";
if ($ dept == 78) echo "Hauts de Seine";
if ($ dept == 91) echo "Yvelines";
if ($ dept == 93) echo "Seine Saint Denis";
?>

where the variable $ dept would come from a form, for example.


This code can be simplified without multiplying the if statements with the instruction

switch ... case. The latter makes it possible to compare the value of an expression with a

list of predetermined values and steer the script according to the value of this expression.

The syntax of this statement is:

switch (expression)
{
case value1:
instruction block 1;
break;
case value2:
instruction block 2;
break;
........................
case valueN:
instruction block N;
break;
default:
default statement block;
break;
}

If the expression following the switch keyword is value1, the statements that follow the

first case statement are executed, after which the execution passes to the end of the block switch. The same goes for the following values.

If no concordance is found, it is the instructions that follow the default statement that are executed.

The presence of this instruction is not mandatory, but it is recommended to do

against all eventualities, such as input errors, for example.

Each group case must end with a break statement, otherwise the other blocks are

also executed.

The value that follows each case statement can be a literal constant or a

named constant, previously declared to switch using the define keyword.


Several different box instructions may succeed one another before a block

instructions. In this case, the different values indicated triggers the execution of the same code. The previous script becomes the one in the next example.

The switch ... case statement

<? Php
$ dept = 75;
switch ($ dept)
{
//First case
case 75: ←
case "Capital" : ←
echo "Paris"; ←
break;
// Second case
case 78:
echo "Hauts de Seine";
break;
// Third case
case 93:
"Stade de France" box:
echo "Seine Saint Denis";
break;
// more departments ...
// Default case
default:
echo "unknown department in Ile de France";
break;
}
?>

Loop instructions


Loops allow you to repeat basic operations a large number of times without having to rewrite the same code. Depending on the loop instruction used, the number of Iterations can be defined in advance or determined by a particular condition.


The for loop


Present in many languages, the for loop allows to execute several times the

same instruction or block without having to rewrite the same instructions. It's syntax is as follows:

for (expression1; expression2; expression3)
{
// statement or block;
}

expression1 is always evaluated. This is usually the initialization of one or

several variables serving as counter for the loop. expression2 is then evaluated

with a Boolean value: if it is TRUE, the loop continues and the instructions

in the block are executed, otherwise the loop stops. If it is still

true we get an infinite loop, so check that it can be false. expression3

is executed only at the end of each iteration. This is most often an instruction

incrementing the counter variable.

This example creates a document that displays six title levels using <h1> tags

to <h6> in two lines of code only.


<? Php
for ($ i = 1; $ i <7; $ i ++)
{
echo "<h $ i> $ i: Level Title $ i </ h $ i>";
}
?>

The three expressions used in the for loop can contain multiple parts

separated by commas. The loop can in this case be performed on several variables,

as illustrated in this example:


<? Php
for ($ i = 1, $ j = 9; $ i <10, $ j> 0; $ i ++, $ j--)
// $ i varies from 1 to 9 and $ j from 9 to 1
{
echo "<span style = \" border-style: double; border-width: 3; \ "> $ i + $ j = 10 </ span>";
}
?>

The result:

ree

Nested loops


It is possible to nest loops for each other on as many level as desired, the block that follows the first containing all the others. Each variable "counter" declared in a loop can only be used in the loop that declares it and in lower level ones.

The example below creates a multiplication table in an HTML table with two

dimensions, each dimension being managed by a different counter variable, $ i and $ j.


The first for loop is only used to create the header line of the table. The

variable $ i is local to the loop. Reusing the same variable name in the

next loop is therefore of no importance.

Two other nested loops are then used to create the body of the table. The

first iterates the line numbers with the variable $ i, and the second the contents of the table cells with the variable $ j.


Nested for loops


<? Php
echo "<h2> Review your multiplication table! </ h2>";
// Start of the HTML table
echo "<table border = \" 2 \ "style = \" background-color: yellow \ "> <th> & nbsp; X & nbsp; </ th> ";
// Create the first line
for ($ i = 1; $ i <10; $ i ++)
{
echo "<th> & nbsp; $ i & nbsp; </ th>"; ←
}
// End of the loop 1
// Creating the body of the table
// Loops for creating table content
for ($ i = 1; $ i <10; $ i ++) ←
{
// Create the first column
echo "<tr> <th> & nbsp; $ i & nbsp; </ th>";
// Filling the table
for ($ j = 1; $ j <10; $ j ++) ←
{
echo "<td style = \" background-color: red; color: white \ "> & nbsp; & nbsp; <b>". $ I * $ j.
"& nbsp; & nbsp; </ td>";
}
echo "</ b> </ tr>";
}
echo "</ table>"
?>

The result:


ree

The while loop


The for loop obliges to specify the limit values ​​for which the loop stops. Unless you use an if statement to stop it with the statement break, these limit values ​​must be known.

The while loop refine this behavio performing a repetitive action as long as a condition is verified or any expression is evaluated to TRUE and thus stop it when it is no longer

verified (evaluated at FALSE).

The while loop allows, for example, to display all the results provided after

querying a database, without knowing the exact number in advance. The

syntax of this statement is as follows:

while (expression)
{
// Block of instructions to repeat
}

The expression specified must be able to be evaluated in a Boolean way by PHP and be able to change value during the script, otherwise the loop would be infinite.

The following example:

$ a = "yes";
while ($ a) {echo $ a; }

is an infinite loop, because $ a evaluates to TRUE as a nonempty string.

Similarly, in the following code:

$ a = 54;
while ($ a> 100) {echo $ a; }

the echo $ a statement is never executed because the expression $ a> 100 contained in while is always wrong.


The example below performs a series of random number runs between 1 and 100 thanks to the rand() function, with the additional condition that the drawn number is a multiple of 7. The script displays the numbers drawn until finding a multiple of 7.


Example: Draw a multiple of 7 with a while loop

<? Php
$ n = 1;
while ($ n% 7! = 0) ←
{
$ n = rand (1,100); ←
echo $ n, "& nbsp; /";
}
?>

You get, for example, the sequence of numbers 72/79/50/95/11/43/18/49 /

(This sequence obviously varies with each draw).


The do ... while loop


The do ... while loop adds precision to the while loop. In this one, indeed, if

the Boolean expression evaluates to FALSE, the statements it contains are

never executed. With the do ... while statement, the condition is not evaluated

after a first execution of the instructions of the block between do and while.


The syntax of the do ... while loop is:

do {
// block of instructions
}
while (expression);

The script in this example is similar to previous example, but it is no longer needed

this time to initialize the variable $ i to 1 because the divisibility by 7 is tested only after the first draw.


Draw with a loop do ... while

<? Php
do
{
$ n = rand (1,100);
echo $ n, "& nbsp; /";
}
while ($ 7% n! = 0); ←
?>

The results obtained are similar.


The foreach loop


Introduced from PHP 4.0, the foreach statement allows you to browse

quickly all the elements of a table, which is also a for loop, but

foreach is much more effective.

The foreach loop is particularly effective for listing associative arrays

it is not necessary to know either the number of elements or the keys. Its syntax is

variable depending on whether you want to recover only the values ​​or values ​​and the

keys (or clues).


To read the values ​​alone, the first syntax is:


foreach ($ array as $ value)
{
// block using the value of the current element
}

The variable $ value contains successively each of the values ​​of the array. It imports

however, not to use an existing variable name, otherwise its value is

crushed. Variables used in a foreach loop are not local to the loop

and thus keep the value of the last element read throughout the script.


To read values ​​and keys (or indices), the second syntax is:

foreach ($ array as $ key => $ value)
{
// block using the value and the key of the current element
}

Here, the variable $ cle successively contains the index or the key of each of the elements of the table in numerical order for indexed tables and in order of creation of

elements for associative arrays. The variable $ value contains the value

associated with the current key or index.

In both cases, the $ array variable can be replaced by an expression whose

value is of the array type, as could be the case, for example, of a function

returning a painting. This instruction is used extensively to read all

results obtained after querying a database.

This example first creates an index table containing the squares of 2 using

a simple for loop and then reads all the elements using a foreach loop.


<? Php
// Create the 9-element array
for ($ i = 0; $ i <= 8; $ i ++)
{
$ tab [$ i] = pow (2, $ i); ←
}
$ val = "A value";
echo $ val, "<br />";
// Reading the values ​​of the table
echo "The squares of 2 are:";
foreach ($ tab as $ val) ←
{echo $ val. ":";}
?>

The following result is displayed:

The squares of 2 are: 1: 2: 4: 8: 16: 32: 64: 128: 256:

Comments


Post: Blog2_Post
  • Facebook
  • Twitter
  • LinkedIn

©2018 by IT basics.. Proudly created with Wix.com

bottom of page