Control structures. One-time inclusion constructs require_once and include_once

20.10.2023 Radiators

Operations and operators of the C programming language. Examples of programs.

Control structures and basic constructs of programming languages

A program located in the computer's memory occupies a certain area of ​​memory at the time of execution. At each moment in time, the state of the program is characterized by two types of information:

The state of some memory cells, which we understand as variables;

The active point of the program, that is, the program command that is currently being executed.

Consequently, we can distinguish two main classes of actions that a computing system can perform:

Actions that allocate memory area for program variables (descriptions).

Actions that change the point of program execution (operators, instructions, constructs).

Various sets of actions of the second class are also called control structures.

Typically, statements in a program are executed one after another in the order in which they are written. This is called sequential execution. Various C statements, which we will discuss shortly, give the programmer the ability to indicate that the next statement to be executed may be different from the next one in the sequence. This is called transfer of control.

During the 1960s, it became clear that the uncontrolled use of control transfer was at the root of most of the difficulties experienced by software development teams. The blame was placed on the goto statement, which allows the programmer to transfer control in a program to one of a very wide range of possible addresses. The concept of so-called structured programming has become almost synonymous with “eliminating the goto statement.”

Bohm and Jacopini's research showed that programming is possible without goto statements at all. Changing the programming style to “programming without goto” has become an epoch-making motto for programmers. But it wasn't until the 1970s that large circles of professional programmers began to take structured programming seriously. The results were impressive, as software development teams reported reduced development time, more frequently delivering systems on time, and completing projects within budget. The key to success is simply that programs created using structured programming techniques are more understandable, easier to debug and modify, and, most importantly, more likely to be written without errors.
Work by Bohm and Jacopini in 1966 showed that all programs can be written using just three control structures, namely the sequential structure, the selection structure, and the repetition structure. This result was established by Bohm and Jacopini in 1966 by proving that any program can be converted into an equivalent program consisting only of these structures and their combinations. The sequential structure is essentially built into the C language. Unless otherwise specified, the computer automatically executes C statements one after another in the order in which they are written.

So, a program for solving a problem of any complexity can be composed of three structures, called following (chain), branching and loop. Each of these control structures is implemented in a programming language by a set of corresponding constructs.

Management structures include:

· following structure;

· branching structure;

Hello dear novice programmers.

You probably already understand from previous articles that a program consists of expressions, strings, numbers, operators, functions that are executed in a certain sequence.

The order of program execution is determined by the programmer, and he uses language control constructs for this. That is, a control structure is a command for one or another order of program execution.

Before moving on to the description of control constructions, I must warn you that you will see many familiar names, since the construction can be operators, functions, loops, which we have already discussed in previous articles.

Constructions (possible definitions - instruction, command) can be either single-line or compound, that is, assembled into a block. A block is also a separate structure, sequentially executing the structures contained in it.

There are six main groups of control constructs in PHP. This:

1. Conditional statements.
2. Cycles.
3. Designs of choice.
4. Ad designs.
5. Value return constructs.
6. Constructions of inclusions.

Let's look at them in detail, and everything in order.

Conditional statements

We have already become acquainted with the conditional operators if, else, elseif in the article “PHP Operators”, so now, considering them as control structures, we will be able to repeat what we have covered, which, as we know, is never superfluous.

Conditional statements are the most frequently used constructs, not only in PHP, but in all algorithmic programming languages.

Single line example if constructs

if ($next == 0 )
{
echo "This is a programming language construct";
}
?>

This example of an if statement specifies that the variable $next must be equal to zero. If this condition is true, then echo will be executed. If not, a blank page will open.

The following will be an example of a composite structure.

$next = 0 ;
if ($next == 0 )
{
echo $vegetables " Vegetables
";
echo $fruit. " Fruits
";
echo $berries. " Berries
";
}
?>

Here, the $next variable is also assigned the value 0, and the if construct, having checked it, executes a block of echo constructs.

Please note that to break a line in php, we use the tag familiar to us from html
. In the future, we will come across html tags used in PHP code more than once.

And I’ll also note that indentations in PHP do not matter, and only improvements in code readability are applied.

In the previous example, we considered the option when the instruction is executed if the specified condition is true.

Now imagine that we need to execute some statement not only when the condition of the if construct is true, but also when the condition is not true.

In this case it applies else construct

$next = 1 ;
if ($next == 0 )
{
echo $vegetables . "Vegetables";
}
else
{
echo $fruit . "Fruits";
}
?>

In this case, it is not a blank page that opens, but a “Fruit” entry.

elseif construct

This construction further expands the capabilities of the if and else constructs. Imagine we have more than two statements, one of which must be executed.

In this case, the elseif construction is added to the previous constructions.

$next = 0 ;
if ($next == 0 )
{
echo $vegetables . "Vegetables";
}
elseif ($next == 0 )
{
echo $fruit . "Fruits";
}
else
{
echo $berries . "Berries";
}
?>

In theory, the number of elseifs is unlimited. And no matter how many there are, the program will check each one until it finds the correct option, that is, true .

Selection constructs

Very often, with a large number of operators, the use of the elseif construction becomes inconvenient due to the large amount of code.

In this case, it comes to the rescue switch-case design, you can switch switch

The switch-case construction is similar in its action to the if-else construction, but unlike the latter, it allows you to get more than two options as a result.

The body of the construct is enclosed in curly braces, and for each value to be processed, a case statement is used, ending with a colon, followed by a terminating break statement.

$next= "Fruit";
switch ($next) (
case "Vegetables":
echo "Potatoes";
break ;
case "Fruit":
echo "Apples";
break ;
case "Berries":
echo "Cherry";
break ;
}
//Apples are displayed

In this example, the condition will first be processed, then a case statement with a value matching this condition will be found, and only after that the switch construct will begin to be executed.

For values ​​not specified in the task, in the switch-case construct, the default operator is used.

$next= "Mushrooms";
switch ($next) (
case "Vegetables":
echo "Potatoes";
break ;
case "Fruit":
echo "Apples";
break ;
case "Berries":
echo "Cherry";
break ;
default:
echo "Champignons";
}
//Champignons are displayed
?>

If you omit the break statement, the program will process and display all the values ​​of the switch-case construct

$next= "Vegetables";
switch ($next) (
case "Vegetables":
echo "Potatoes";
case "Fruit":
echo "Apples";
case "Berries":
echo "Cherry";
default:
echo "Champignons";
}
/* Output
Potato
Apples
Cherry
Champignon */

?>

Another feature of the switch-case design is the ability to combine several options into one expression.

$next= "Maple";
switch ($next) (
case "Vegetables":
case "Fruit":
case "Berries":
echo "Potatoes
Apples
Cherry";
break ;
case "Maple":
case "Oak":
case "Spruce":
echo "Forest";
break ;
default:
echo "Champignons";
}
// Outputs Forest
?>

Cycles, or repetition structures.

Loops are intended for repeated (unlike the if construct) execution of the operators that make up the body of the construct.

The process of executing a loop is called iteration.

There are three types of loops in php:

1. while and do-while are loops with an undetermined number of iterations.
2. for - a loop with a predetermined number of iterations.
3. foreach - cycle of processing (enumeration) of the array.

while construct

An example of a simple loop with one statement; usually there are more.

$next = 1 ;
while ($next<= 8 )
{
echo $next. "
" ;
$next++;
}
//Displays numbers from 1 to 8. Tag
arranges them in a column

?>

Let's take a closer look at what's happening here, that is, how this program works.

The first line declares the variable $next , which is assigned the value one. Assigning a value is called variable initialization.

In the second line, the program checks the while condition ($next<= 8) , которое будет являться истиной (true).

The third line executes the first loop because one is less than 8, and this qualifies as true

In the fourth, the variable, which in this case is an operator, is assigned an increment operator (++), which increases each subsequent value of the $next operator by one.

And the program will process and display every integer following one until it reaches 9. And since 9 turns out to be false, the loop will end.

do-while construct differs in that the loop condition is checked not before, but after the iteration.

As a result, before the loop completes, one iteration will be executed, which is false

$next = 1 ;
do
{
echo $next;
}
while ($next++<= 8 );
//Prints numbers from 1 to 9 on one line.
?>

As you can see, even though 9 is false, the next iteration was still completed, after which the program checked the condition and the loop ended.

The for construct, or a loop with a counter, is similar in operation to the while loop, but has a more compact form of notation.

It is best used when the number of iterations is known before the start of the loop, and with its help, you can perform actions more complex than simple sorting through counter values.

In the following example, we will write a table of contents for a small book.

for ($next = 1 ; $next< 5 ; $next++)
{
echo "- Page" . $next . "
";
}
/*Outputs
-Page 1
-Page 2
-Page 3
-Page 4
-Page 5 */

?>

Let us consider in detail the three expressions written in the condition (parentheses) of the loop.

$next = 1; — a counter variable that starts counting from one.
$next< 5; — определяет продолжительность цикла.
$next++ — defines the step for changing the counter value. In our case it is equal to one.

Expressions are separated by semicolons. You can put several commands in one expression and separate them with commas. Then the same table of contents can be done a little differently

for ($next= 1 , $nev= 1 , $page= "-Page"; $next<= 5 ; $nev++, $next=$nev)
{
$page=$page . "-";
echo $page, $next . "
";
}
/*Outputs
-Page-1
-Page--2
-Page---3
-Page----4
-Page-----5 */

?>

Another feature of for is the ability to dispense with the echo construct.

True, this option is not particularly welcome, since it somewhat complicates the readability of the code due to its unusual nature, but it still has a right to exist.

In it, the print construct is introduced into the loop condition

for ($next= 1 ; $next<= 5 ; print $next, print "
" , $next++);
/*Outputs
1
2
3
4
5 */

?>

The echo construct cannot be entered into a for condition.

All of the above constructs, except do-while , have an alternative form of notation - without curly braces.

In this case, the line with the construction and condition ends with a colon, and the entire block is closed with the end construction, the continuation of which is the construction to which it is applied: endif, endwhile, and so on.

$next = 1 ;
while ($next<= 10 ):
echo $next;
$next++;
endwhile ;
?>

foreach construct is a special type of loop designed only to iterate through an array.

$next[ "tomato"] = "Red";
$next[ "apple"] = "Green";
$next[ "grapes"] = "Sweet";
$next[ "mushroom"] = "White";
foreach ($next as $key => $value)
{

echo "$value $key
";
}
/*Outputs
Red tomato
Green apple
Sweet grapes
Porcini */

?>

To exit the loop immediately, if necessary, there is break construction. After its execution, control is transferred to the expression following the loop.

$next= 0 ;
while ($next++< 10 )
{
if ($next== 7 ) break;
echo "$next
";
}
/*Outputs
1
2
3
4
5
6 */

?>

As you can see, at the seventh iteration the loop was interrupted.

Continue construction, unlike break , interrupts only the current iteration and moves on to the next one.

$next= 0 ;
while ($next++< 5 )
{
if ($next== 3 ) continue ;
echo "$next
";
}
/*Outputs
1
2
4
5 */

?>

As you can see, iteration 3 is missing, as it was interrupted by the continue construct

Ad designs

Declaration constructs in PHP are represented by two elements. These are the declare and typeset constructs.

In fact, they are absolutely identical, and with equal success you can use both one and the other to obtain the same result.

To make the code easier to understand, the declare construct is mainly used. It is used to set commands (directives) for block execution.

Currently two directives are recognized: ticks and encoding

The ticks directive specifies the number of ticks

declare (ticks= 1 );

register_tick_function("tick_handler");

// Function will be executed at every tick
?>

The encoding directive is used to specify the encoding of the entire script.

declare(encoding= "UFT-8");
?>

Inclusion designs

Inclusion constructs are used to enter individual scripts and files into a program. Thanks to them, the program can be assembled from ready-made material.

Inclusion constructs are also used to reduce the amount of script code when you need to enter some text into the code. Then the txt file is entered into the program.

True, in this case, a threat to the security of the script arises, and to solve it, you need to enter a constant into the program along with the txt file, and check its existence in the included files.

In total, there are 4 types of inclusion constructs in PHP, and all of them take only one argument - the path to the file:

include - connects the file to the program, if it is missing, issues a warning;
require - connects the file to the program, and if it is missing, stops the script;
include_once - allows only one-time inclusion of the included file, and if it is absent, issues a warning;
require_once - allows only one-time inclusion of the connected file, and in its absence, stops the script;

The include_once and require_once constructs are convenient because they eliminate confusion when nested includes, when it is possible to re-include files containing function declarations.

Are there really no questions left?


Turn

Only in our country the word “uh-huh” is a synonym for the words “please”, “thank you”, “good afternoon”, “you’re welcome” and “sorry”, and the word “come on” in most cases replaces “goodbye”.

You can't wait for any love like a bus at -30°.

Annotation: Control constructs of the C language are considered: "if-else" and "if-else if" branches, "while" and "for" loops. There are also constructions that are best avoided: “switch”, “do-while”, “goto”. The presentation of a program in the form of a set of functions, prototypes of functions, methods of transferring input and output parameters are considered. The different types of memory are listed: static, stack, dynamic (heap) and ways of working with memory in C. A composite data type "structure" is introduced. The material is illustrated with numerous examples of programs: solving a quadratic equation, calculating a square root, calculating the gcd of two numbers and the extended Euclidean algorithm, printing the first N prime numbers, recursive traversal of a tree, etc.

Control structures

Control constructs allow you to organize loops and branches in programs. There are only a few constructs in C, and half of them don’t need to be used (they are implemented through the rest).

Braces

Curly braces allow you to combine several elementary statements into one compound statement, or block. In all syntactic constructions, a compound operator can be used instead of a simple one.

In C, you can place declarations of local variables at the beginning of a block. Local variables defined within a block are created upon entry into the block and destroyed upon exit.

In C++, local variables can be declared anywhere, not just at the beginning of a block. However, just like in C, they are automatically destroyed when leaving the block.

Here is a program fragment that exchanges the values ​​of two real variables:

double x, y; . . . ( double tmp = x; x = y; y = tmp; )

Here, to exchange the values ​​of two variables x and y, we first store the value of x in the auxiliary variable tmp. Then the value of y is written to x, and the previous value of x stored in tmp is written to y. Since the tmp variable is only needed inside this fragment, we enclosed it in a block and declared the tmp variable inside that block. Upon exiting the block, the memory occupied by the tmp variable will be freed.

if statement

The if statement allows you to organize branching in a program. It has two forms: the "if" statement and the "if...else" statement. The "if" operator has the form

if (condition) action;

the "if...else" operator has the form

if (condition) action1; else action2;

You can use any expression of logical or integer type as a condition. Recall that when using an integer expression, the value "true" corresponds to any non-zero value. When executing an "if" statement, the conditional expression after the if is first evaluated. If it is true, then the action is performed, if false, then nothing happens. For example, in the following fragment, the maximum value of the variables x and y is written to the variable m:

double x, y, m; . . . m = x; if (y > x) m = y;

When executing an "if...else" statement when the condition is true, the action written after the if is executed; otherwise, the action after else is executed. For example, the previous fragment is rewritten as follows:

double x, y, m; . . . if (x > y) m = x; else m = y;

When you need to perform several actions depending on the truth of a condition, you should use curly braces, combining several statements into a block, for example,

double x, y, d; . . . if (d > 1.0) ( x /= d; y /= d; )

Here the variables x and y are divided by d only if the value of d is greater than one.

Curly braces can be used even when there is only one statement after if or else. They improve the structure of the program text and facilitate its possible modification. Example:

double x, y; . . . if (x != 0.0) ( y = 1.0; )

If we need to add another action that performs if "x is non-zero", then we will simply add a line inside the curly braces.

Select from several options: if...else if...

Multiple if...else conditional statements can be written sequentially (ie, the action after the else can again be a conditional statement). As a result, it is realized choice from several options. The selection construct is used very often in programming. Example: given a real variable x, you need to write the value of the function sign(x) into the real variable y.

Any PHP script is formed from a number of constructs. A construct can be statements, functions, loops, conditional statements, even constructs that do nothing (empty constructs). The constructs usually end with a semicolon. Additionally, constructs can be grouped together to form a group of curly brace constructs (...). A group of structures is also a separate structure. PHP language constructs are similar to C language constructs.

There are six main groups of control constructs in PHP. So, the main groups of PHP control constructs and their composition:

  • Conditional statements:
    • else
    • elseif
  • Cycles:
    • while
    • do-while
    • foreach
    • break
    • continue
  • Designs of choice:
    • switch-case
  • Ad designs:
    • declare
    • return
  • Inclusion designs:
    • require()
    • include()
    • require_once()
    • include_once()
  • Alternative syntax for PHP constructs

PHP Conditional Statements

Conditional statements are perhaps the most common constructs in all algorithmic programming languages. Let's look at the basic conditional operators of the PHP language.

if construct

The syntax of the if construct is similar to the if construct in C:

According to PHP expressions, the if clause contains a Boolean expression. If the logical expression is true (true), then the statement following the if construct will be executed, and if the logical expression is false (false), then the statement following the if will not be executed. Here are some examples:

$b ) echo "the value of a is greater than b"; ?>

In the following example, if the variable $a is not null, the string "the value of a is true" will be printed:

"the value of a is true "; ?>

In the following example, if $a is null, the string "the value of a is false" will be printed:

"the value of a is false "; ?>

Often you will need a block of statements that will be executed under a certain conditional criterion, then these statements will need to be placed in curly braces (...) Example:

$b ) ( echo "a is greater than b" ; $b = $a ; ) ?>

The above example will print the message, "a is greater than b" if $a > $b, and then the variable $a will be set to the variable $b. Note that these statements are executed in the body of the if construct.

else construct

Often there is a need to execute statements not only in the body of the if construct, if any condition of the if construct is met, but also if the condition of the if construct is not satisfied. In this situation, you cannot do without the else construct. In general, such a construct will be called an if-else construct.

The syntax of the if-else construct is:

If (boolean_expression) instruction_1; else instruction_2;

The effect of the if-else construct is as follows: if the logical_expression is true, then instruction_1 is executed, otherwise instruction_2 is executed. As in any other language, the else clause can be omitted, in which case nothing is done when obtaining the proper value.

If instruction_1 or instruction_2 must consist of several commands, then they are, as always, enclosed in curly braces. For example:

$b ) ( echo "a is greater than b" ; ) else ( echo "a is NOT greater than b"; } ?>

The if-else construct has another alternative syntax:

If (boolean_expression): commands; elseif(other_logical_expression): other_commands; else: else_commands; endif

Pay attention to the placement of the colon (:)! If you skip it, an error message will be generated. And one more thing: as usual, elseif and else blocks can be omitted.

elseif construct

elseif is a combination of if and else constructs. This construct extends the if-else conditional construct.

Here is the syntax of the elseif construct:

If (boolean_expression_1) statement_1; elseif (boolean_expression_2) statement_2; else operator_3;

A practical example of using the elseif construct:

$b ) ( echo "a is greater than b" ; ) elseif ($a == $b ) ( echo "a is equal to b" ; ) else ( echo "a is less than b" ; ) ?>

In general, the elseif construct is not very convenient, so it is not used so often.

Cycles:

In second place in terms of frequency of use, after conditional constructs (conditional statements), are cycles.

Loops allow you to repeat a certain (and even an indefinite - when the operation of the loop depends on a condition) number of times different operators. These statements are called the body of the loop. The passage of a loop is called an iteration.

PHP supports three types of loops:

  1. Loop with precondition (while);
  2. Loop with postcondition (do-while);
  3. Loop with counter (for);
  4. A special loop for looping through arrays (foreach).

When using loops, it is possible to use the break and continue statements. The first of them interrupts the entire loop, and the second only interrupts the current iteration.

Let's look at PHP loops:

Loop with precondition while

A loop with a while precondition works according to the following principles:

  • The value of a logical expression is calculated.
  • If the value is true, the body of the loop is executed; otherwise, we move on to the statement following the loop.

"The syntax for a loop with a precondition is:"

While (boolean_expression) statement;

In this case, the body of the loop is an instruction. Typically the body of a loop consists of a large number of statements. Here's an example of a loop with a while precondition:

Pay attention to the sequence of operations of the condition $x++<10. Сначала проверяется условие, а только потом увеличивается значение переменной. Если мы поставим операцию инкремента перед переменной (++$x<10), то сначала будет выполнено увеличение переменной, а только затем - сравнение. В результате мы получим строку 123456789. Этот же цикл можно было бы записать по-другому:

// Increment the counter echo $x ; ) // Prints 12345678910 ?>

If we increment the counter after executing the echo statement, we get the string 0123456789. Either way, we have 10 iterations. Iteration is the execution of statements within the body of a loop.

Similar to the if conditional statement construct, you can group statements within the body of a while loop using the following alternative syntax:

While (boolean_expression): statement; ...endwhile;

An example of using an alternative syntax:

Loop with do while postcondition

Unlike the while loop, this loop checks the value of the expression not before, but after each pass (iteration). Thus, the body of the loop is executed at least once. The syntax for a loop with a postcondition is:

Do (loop_body; ) while (logical_expression);

After the next iteration, it is checked whether the logical_expression is true, and if so, control is transferred again to the beginning of the loop, otherwise the loop is terminated. PHP developers did not provide an alternative syntax for do-while (apparently due to the fact that, unlike application programming, this loop is rarely used when programming web applications).

An example of a script showing the operation of a loop with a do-while postcondition:

12345678910

Loop with a for counter

A counter loop is used to execute the body of the loop a specified number of times. Using the for loop, you can (and should) create constructs that will perform actions that are not at all as trivial as simply iterating over a counter value.

The syntax for the for loop is:

For (initializing_commands; loop_condition; after_iteration commands) ( loop_body; )

The for loop begins its work by executing initialization_commands. These commands are executed only once. After this, the loop_condition is checked, if it is true, then the loop_body is executed. After the last statement of the body is executed, the after_iteration commands are executed. Then the loop_condition is checked again. If it is true, the body_of_the loop and the commands_after_iteration are executed, etc.

This script outputs: 0123456789

There is an option to output the line 12345678910:

In this example, we ensured that the counter was incremented when checking a logical expression. In this case, we did not need commands to be executed after the iteration.

If you need to specify several commands, they can be separated by commas, example:

Here's another, more practical example of using multiple commands in a for loop:

// Outputs Points.Points..Points...Points.... ?>

The considered example (and indeed any for loop) can also be implemented using while, but it will not look so elegant and concise.

There is an alternative syntax for the for loop:

For(initial_commands; loop_condition; post_iteration_commands): operators; endfor;

Foreach array loop

PHP4 introduced another special type of loop - foreach. This loop is designed specifically for iterating through arrays.

The syntax for a foreach loop is as follows:

Foreach (array as $key=>$value) commands;

Here the commands are executed cyclically for each element of the array, with the next key=>value pair ending up in the $key and $value variables. Here's an example of how the foreach loop works:

$value ) ( echo " $value $key
" ; } ?>

The above script outputs:

Andrey Ivanov Boris Petrov Sergei Volkov Fedor Makarov

The foreach loop has another form of notation that should be used when we are not interested in the value of the key of the next element. It looks like this:

Foreach (array as $value) commands;

In this case, only the value of the next array element is available, but not its key. This can be useful, for example, for working with list arrays:

$value
"
; } ?>

Attention: The foreach loop operates not on the original array, but on a copy of it. This means that any changes that are made to the array cannot be "seen" from the body of the loop. This allows, for example, to use not only a variable as an array, but also the result of some function that returns an array (in this case, the function will be called only once - before the start of the loop, and then work will be done with a copy of the returned value).

break construct

Very often, in order to simplify the logic of a complex loop, it is convenient to be able to interrupt it during the next iteration (for example, when some special condition is met). This is why the break construct exists, which immediately exits the loop. It can be specified with one optional parameter - a number that indicates which nested loop should be exited from. The default is 1, i.e. exits the current loop, but other values ​​are sometimes used. The syntax of the break construct is:

Break; // By default break(cycle_number); // For nested loops (the number of the interrupted loop is indicated)

Here are some examples:

Iteration $x
"
; } // When $x is 3, the loop breaks ?>

The above script outputs:

Iteration 1 Iteration 2

If we need to interrupt the work of a specific (nested) loop, then we need to pass a parameter to the break construct - loop_number, for example, break(1). The numbering of the cycles is as follows:

For (...) // Third loop ( for (...) // Second loop ( for (...) // First loop ( ) ) )

Continue construction

The continue construct, just like break, only works “in pairs” with cyclic constructs. It immediately ends the current iteration of the loop and moves on to a new one (if the loop condition for the loop with a precondition is satisfied, of course). In the same way as for break, for continue you can specify the nesting level of the loop, which will be continued upon return of control.

Basically continue allows you to save the number of curly braces in your code and increase its readability. This is most often needed in filter loops, when you need to iterate through a certain number of objects and select from them only those that satisfy certain conditions. Here is an example of using the continue construct:

Iteration $x
"
; } // The loop will only break on the third iteration ?>

The script in question outputs:

Iteration 1 Iteration 2 Iteration 4 Iteration 5

Proper use break And continue allows you to significantly improve the “readability” of the code and the number of else blocks.

Designs of choice:

Often, instead of several if-else statements located in a row, it is advisable to use a special switch-case selection construct. This construction is intended to select actions depending on the value of the specified expression. The switch-case construction is somewhat reminiscent of the if-else construction, which, in fact, is its analogue. The choice construct can be used if there are many possible options, for example, more than 5, and for each option you need to perform specific actions. In this case, using the if-else construct becomes really inconvenient.

The syntax of the switch-case construct is:

Switch(expression) ( case value1: commands1; case value2: commands2; . . . case valueN: commandsN; ] )

The operating principle of the switch-case design is as follows:

  • The value of the expression is calculated;
  • A set of values ​​is viewed. Let value1 be equal to the value of the expression calculated in the first step. If the break construction (operator) is not specified, then commands i, i+1, i+2, ... , N will be executed. Otherwise (there is a break), only command number i will be executed.
  • If no value from the set matches the value of the expression, then the default block is executed, if one is specified.

Here are examples of using the switch-case construct:

// Use if-else if ($x == 0 ) ( echo "x=0
" ; ) elseif ($x == 1 ) ( echo "x=1
" ; ) elseif ($x == 2 ) ( echo "x=2
" ; } // Use switch-case switch ($x) ( case 0 : echo "x=0
" ; break ; case 1 : echo "x=1
" ; break ; case 2 : echo "x=2
" ; break ; ) ?>

The above script prints x=1 twice. Another example of using the switch-case construct:

This script displays "This is an Apple".

The switch construct is executed in stages. At first, no code is executed. Only when a case construct is found with a value that matches the value of the switch expression does PHP begin executing the constructs. PHP continues executing until the end of the switch block, until a break statement is encountered. If you do not use break constructs (operators), the script will look like this:

" ; case 1 : echo "x=1
" ; case 2 : echo "x=2
" ; } // Without using break prints// x=0 // x=1 // x=2 ?>

The statement list for case can also be empty, it simply transfers control to the statement list until the next case construct:

"x is less than 3, but not negative"; break ; case 3 : echo "x=3" ; ) ?>

When no value from the set matches the value of the expression, then the default block is executed, if specified, for example:

"x is not equal to 0, 1 or 2"; } ?>

This script outputs "x is not equal to 0, 1 or 2" because the variable $x=3.

The switch-case construct also has an alternative syntax:

Switch(expression): case value1: commands1; . . . case valueN: commandsN; ] endswitch;

A practical example of using an alternative syntax for the switch-case construct:

"x is not equal to 0, 1 or 2"; endswitch ; ?>

As you already understood, this script outputs "x is not equal to 0, 1 or 2" since $x=3.

Ad designs:

The declare construct

The declare declaration construct is used to set execution directives for a block of code. The declare syntax is similar to the syntax of other PHP control constructs:

Declare (directive) instruction;

The directive allows you to set the behavior of the declare block. Currently there is only one directive available in PHP - tick. The instruction is part of the declare block.

How the instruction(s) are executed depends on the directive.

Design declare can be used in the global scope, affecting all code after it.

The tick directive

tick is an event that occurs for every N-lower level instructions executed by the parser within a block declare. The events that occur on each tick are determined by the function register_tick_function().

Return constructs:

return construct

The rerurn construct returns values, primarily from user-defined functions, as function query parameters. When return is called, execution of the user-defined function is interrupted, and the return construct returns specific values.

If the return construct is called from the global scope (outside of user-defined functions), then the script will also exit, and return will also return certain values.

Primarily, the return construct is used to return values ​​by user-defined functions.

Return values ​​can be of any type, including lists and objects. Returning causes the function to complete execution and transfers control back to the line of code in which the function was called.

An example of using the return construct to return values ​​of type integer:

An example of returning arrays using the return construct:

In order for a function to return a result by reference, you need to use the & operator both when declaring the function and when assigning the return value to the variable:

As we can see, the design return very convenient for use in user functions.

Inclusion designs:

Inclusion constructs allow you to assemble a PHP program (script) from several separate files.

There are two main include constructs in PHP: require And include.

The construct of require inclusions

The require construct allows you to include files in a PHP script before the PHP script is executed. The general syntax for require is:

Require filename;

When starting (precisely at startup, not during execution!) of the program, the interpreter will simply replace the instruction with the contents of the file file_name (this file may also contain a PHP script, framed, as usual, with tags). Moreover, it will do this immediately before starting the program (unlike include, which is discussed below). This can be quite convenient for including various template pages with HTML code in the script output. Here's an example:

Header.html file:

It is a title

Footer.html file:

Home Company, 2005.

Script.php file

// The script displays the body of the document itself require "footer.htm" ; ?>

Thus, the require construct allows you to assemble PHP scripts from several separate files, which can be either HTML pages or PHP scripts.

The require construct supports remote file inclusions (since PHP 4.3.0). For example:

// The following example works require ; ?>

The require construct allows you to include remote files if this feature is enabled in the PHP configuration file. More details below.

The include construct

The include clause is also used to include files in PHP script code.

Unlike the require construct, the include construct allows you to include files in the PHP script code while the script is running. The syntax of the include construct is as follows:

Include filename;

Let us explain the fundamental difference between the require and include constructs using a specific practical example. Let's create 10 files with names 1.txt, 2.txt and so on until 10.txt, the contents of these files are simply the decimal digits 1, 2 ...... 10 (one digit in each file). Let's create the following PHP script:

// Create a loop with the include construct in its body for ($i = 1 ; $i<= 10 ; $i ++ ) { include "$i.txt"; } // Included ten files: 1.txt, 2.txt, 3.txt ... 10.txt // Result - output 12345678910 ?>

As a result, we will get an output consisting of 10 digits: "12345678910". From this we can conclude that each of the files was included once, right during the execution of the loop! If we now put require instead of include, the script will generate a fatal error. Compare the results.

PHP converts the script into an internal representation, parsing the script lines one by one until it reaches the include clause. Having reached include, PHP stops translating the script and switches to the file specified in the include. Thus, due to this behavior of the translator, the performance of the script is reduced, especially with a large number of files included using include. There are no such problems with require, since files are included using require before the script is executed, that is, at the time of translation, the file is already included in the script.

Thus, it is more appropriate to use the require construct where dynamic inclusion of files in the script is not required, and use the include construct only for the purpose of dynamically including files in the PHP script code.

Design include supports inclusion of remote files (since PHP 4.3.0). For example:

// The following example doesn't work because it tries to include a local file// The following example works include "http://www.example.com/file.php?foo=1&bar=2"; ?>

The include construct allows you to include remote files if this feature is enabled in the PHP configuration file. More details below.

One-time inclusion constructs require_once and include_once

In large PHP scripts, include and require statements are used very often. Therefore, it becomes quite difficult to control how not to accidentally include the same file several times, which most often leads to an error that is difficult to detect.

PHP provides a solution to this problem. By using the one-time include constructs require_once and include_once, you can be sure that the same file will not be included twice. The one-time inclusion constructs require_once and include_once work in the same way as require and include, respectively. The only difference in their operation is that before including a file, the interpreter checks whether the specified file has been included previously or not. If yes, the file will not be included again.

The one-time include constructs also require_once and include_ince also allow you to include remote files if enabled in the PHP configuration file. More details below.

Including remote files

PHP allows you to work with URL objects like regular files. Packers, available by default, are used to work with remote files using the ftp or http protocol.

If "fopen wrapper URLs" are enabled in PHP (as in the default configuration), you can specify a file to be included using a URL (via HTTP) instead of a local path. If the target server interprets the target file as PHP code, variables can be passed to the include file using a URL query string, as in HTTP GET. Strictly speaking, this is not the same as including a file and having it inherit the scope of the parent file's variables; after all, the script runs on a remote server, and the result is then included in the local script.

In order for remote inclusion of files to be available, you need to set allow_url_fopen=1 in the configuration file (php.ini).

Please note: Versions of PHP for Windows prior to PHP 4.3.0 do not support the ability to use remote files by this feature, even if the allow_url_fopen option is enabled.

/* This assumes that www.example.com is configured to parse .php * files rather than .txt files. Also "Works" here means that the variables * $foo and $bar are available in the included file. */ //Won't work because file.txt is not processed by www.example.com like PHP include "http://www.example.com/file.txt?foo=1&bar=2"; // Will not work because it is looking for the file "file.php?foo=1&bar=2" in the local // file system. include "file.php?foo=1&bar=2" ; // The following example works: include "http://www.example.com/file.php?foo=1&bar=2"; $foo = 1 ; $bar = 2 ; include "file.txt" ; // Works include "file.php" ; // Works ?>

See also remote files, fopen() and file() for more information.

Additionally:

You probably already know how to insert HTML code into the body of a script. To do this, simply close the bracket?> code, and then open it again with

You may have noticed how ugly it looks. However, if you put a little effort into the design, it won't be so bad. Especially if you use the alternative syntax of if-else and other language constructs.

Most often you need to do not insert HTML inside the script, but insert code inside HTML. This is much easier for the designer, who may want to redesign the script in the future, but will not be able to figure out what to change and what not to touch. Therefore, it is advisable to separate the HTML code from the program (script), for example, place it in a separate file, which is then connected to the script using the include construct. For example, here's what a script that greets a user by name would look like, using the alternative if-else syntax:

Hello, !

method=get> Your name:

Agree that even a person completely unfamiliar with PHP, but well versed in HTML, can easily understand what’s what in this scenario. Let's look at an alternative syntax for some constructs in the context of using it in conjunction with HTML:

Alternative syntax for if-else

...HTML code......HTML code...

Alternative syntax for while loop

...HTML code...

An example of using an alternative syntax for a while loop:

As we can see, using an alternative syntax allows you to make PHP scripts readable in cases where you need to actively operate PHP in conjunction with HTML code.