Note: The adaptive version of the site is activated, which automatically adapts to the small size of your browser and hides some details of the site for ease of reading. Enjoy watching!

Hello dear readers and regular subscribers! It's time to continue the series of articles about PHP and today we will study such a basic and at the same time very important thing as loops. What's the first thing you need to know about cycles? And the fact that they are used everywhere and everywhere, and Joomla templates, VirtueMart, Wordpress, OpenCart and any other CMS are no exception.

What is a cycle? Cycle is the repeated repetition of the same piece of code. How many repetitions need to be done depends on the cycle counter, which we ourselves create and can control. This is very convenient, for example, when we need to display products in an online store category, display blog posts, display comments on an article or product; all menus in CMS (website engines) are also made using cycles. In general, loops are used very often.

But before moving on to the loops themselves, first you need to understand such a thing as operators increment And decrement.

The ++ (increment) operator increases the value of a variable by one, while the -- (decrement) operator decreases the value of a variable by one. They are very convenient to use in loops as a counter, and in programming in general. There are also PRE increment/decrement and POST increment/decrement:

PRE increment/decrement ++$a Increments $a by one and returns the value of $a. --$a Decrements $a by one and returns the value of $a. POST increment/decrement $a++ Returns the value of $a and then increments $a by one. $a-- Returns the value of $a and then decrements $a by one.

For example:

$a = 1; echo "Output number: " . $a++; // Output the number: 1 echo "Output the number: " . $a; // Output the number: 2 echo "Output the number: $a"; $a += 1; // same as in the first line$a = 1; echo "Output number: " . +$a; // Output the number: 2 echo "Output the number: " . $a; // Output the number: 2 $a += 1; echo "Output number: $a"; // the same as in the first line of this block

for loop

for (part A; part B; part C)( // Any code, as many lines as you like; )

The for loop consists of 3 parts and the body itself. Part A it just does what it says, usually in 90% of cases it creates a loop counter. Part B- this is, roughly speaking, already familiar to us if, that is, checking for truth (true?). If the condition is true, that is true, then PHP goes inside the loop and continues executing it. Part C- the same as part A, as a rule, in Part C we do some kind of transformation with the counter. For example:

"; ) echo "EXITED THE LOOP and moved on through the code..."; ?>

Now about the algorithm of the for loop. The first thing PHP sees for is it goes to part A and executes it just once (see image below). Next, PHP goes to part B and checks whether it is true or false. If true, then it executes the body of the loop and only after that moves to part C. After this, PHP again goes to part B and checks whether it is still true there or not. If not, then the loop ends, if yes, then it continues until part B contains false.

The result of the previous example:

While Loop

while (part B)( // Any code, as many lines as you like; )

As you can see, there is no part A and part C, only the condition remains from the for loop, that is, part B. If we need to use a counter, then we must place it inside the while loop, among the rest of the code, this will be part C. A create The counter is needed before the start of the while construct:

Part A; while (part B)( // Any code, as many lines as desired; Part C; )

Let's convert the previous for loop into a while loop:

"; $i++; ) echo "EXITED THE LOOP and moved on through the code..."; ?>

The result will be exactly the same. What to use: a for loop or a while loop is a matter of taste, see what is more convenient and logical for you, there is no difference.

Do... while loop

Less common of all cycle types. Essentially this is an inverted while. Its trick is that PHP will definitely enter the body of the do... while loop at least once (the first time), because in this loop there is a condition at the end:

Part A; do( // Any code, as many lines as you like; Part C; )while(Part B);

"; $i++; )while($i< 8); echo "ВЫШЛИ ИЗ ЦИКЛА и пошли дальше по коду..."; ?>

It is important to understand: in all three types cycles have no required parts.

An example of a for loop without part A and part C:

For(;$i > 8;)( // your code )

An example of a for loop without all three parts:

For(;;)( // classic endless loop)

That is, all semicolons still remain in for loop, such syntax!

Infinite loops

An infinite loop is a developer error in which the page will never be able to load to the end, since the loop condition (part B) will always be true. For example:

"; $i++; )while($i != 0); echo "EXITED THE LOOP and moved on through the code..."; ?>

Result:

I showed only part of this, because everything doesn’t fit on the screen. This is how your browser and the server of your site will suffer endlessly until the browser crashes after 30 seconds. And all because in the example above, the $i variable will never be equal to zero, it is initially equal to 1 and is constantly increasing.

That is, the developer was inattentive when he came up with such a condition.

Cycle management

Operator break. There are situations when we do not need the loop to play out all the iterations (repetitions). For example, at some certain moment we want to interrupt it and continue execution with the code below:

"; if ($i === 5) break; // exit the loop if $i is equal to 5 $i++; ) echo "I can only count up to 5:("; ?>

Result:

In the example above, as soon as we reached five, PHP exited the loop, otherwise it would have counted to 7.

Continue operator also interrupts the execution of the loop, but unlike break, continue does not exit the loop, but returns the PHP interpreter back to the condition (to part B). Example:

"; ) echo "Did I miss something?"; ?>

Result:

We just missed the number 5 because PHP didn't get to echo.

A loop can be nested within a loop. In this case, the continue and break statements apply only to one loop, the one in which they are located. That is, in other words, they transfer to one level, and not across all. Example:

But we ourselves can choose how many levels we need to jump through:

"; $i++; $i=1; $k=1; while ($k< 8) { echo "Итерация $k номер ". $k . "
"; if ($k === 5) break 2; $k++; ) ) ?>

Result:

Naturally, we cannot set a number greater than the number of nested loops we have.

foreach loop

Last in order, but most important in importance, is the foreach loop. Used only for enumeration and objects (it’s too early to teach them). Example syntax:

"; } ?>

Result:

This was a short foreach construct, but it also has an extended version, which, in addition to the values ​​of the array cells, also displays the names of the cells (keys):

$value) ( ​​echo "In section " . $key . " there is an article called: ". $value ."
"; } ?>

Result:

I draw your attention to the fact that we can call the variables whatever we want, even $key and $value, even $xxx and $yyy.

If it is an array, then we use only the foreach loop and no others. It is this cycle that is used throughout VirtueMart, and indeed everywhere.

Last update: 11/1/2015

To perform repeatable actions in PHP, as in other programming languages, loops are used. PHP has the following types of loops:

for loop

The for loop has the following formal definition:

For ([initialize counter]; [condition]; [change counter]) ( // actions )

Consider the standard for loop:

"; } ?>

The first part of the loop declaration - $i = 1 - creates and initializes the counter - the variable $i. And before the loop is executed, its value will be 1. Essentially, this is the same as declaring a variable.

The second part is the condition under which the loop will be executed. In this case, the loop will run until $i reaches 10.

The third part is incrementing the counter by one. Again, we don't necessarily need to increase by one. You can decrease: $i--.

As a result, the loop block will run 9 times until the value of $i becomes 10. And each time this value will increase by 1. Each individual repetition of the loop is called an iteration. Thus, in this case there will be 9 iterations.

while loop

The while loop checks the truth of some condition, and if the condition is true, then the block of loop expressions is executed:

"; $counter++; ) ?>

If there is only one instruction in the while block, then braces block can be omitted:

"; ?>

do..while loop

The do..while loop is similar to the while loop, only now the loop block is executed, and only then the condition is tested. That is, even if the condition is false, the loop block will be executed at least once:

"; $counter++; ) while($counter<10) ?>

Continue and break statements

Sometimes a situation arises when you need to exit a loop without waiting for it to complete. In this case, we can use the break statement:

80) ( break; ) echo "The square of $i is equal to $result
"; } ?>

And if suddenly the result of the operation turns out to be more than 80, then the loop exits.

The continue operator is also used to control loops. It moves to the next iteration of the loop:

"; } ?>

When executing the program, when the value of $i becomes equal to 5, the transition to the next iteration will occur, and all other expressions that follow the continue operator will not be executed.

If inside a line enclosed in single quotes, a backslash "\" occurs before any other character (other than "\" and """), then it is treated as a regular character and is printed like all others. Therefore, a backslash only needs to be escaped if it is at the end lines before the closing quote.

There are a number of character combinations in PHP that begin with the backslash character. These are called escape sequences, and they have special meanings that we'll talk about a little later. So, unlike the other two syntaxes, variables and escape sequences for special characters that appear in strings enclosed in single quotes are not processed.

echo "You can also insert into lines
newline character thus,
because it's normal"
;
// Output: To output " you need
// put \ in front of it
echo "To display \" you need to before ".
"put her \\";
// Outputs: Do you want to delete C:\*.*?
echo "Do you want to delete C:\\*.*?";
// Output: This will not insert: \n
// new line
echo "This will not insert:\nnewline";
// Outputs: $expand variables also
// $either is not substituted
echo "$expand variables are also $either".
"not substituted";
?>

16.1. Example. Using escape sequences

17. Double quotes

If the string is enclosed in double quotes """, PHP recognizes more escape sequences for special characters.

Some of them are shown in the table.
Table. Control sequences.

We repeat, if you want to escape any other character, the backslash will be printed too!

The most important property of double-quoted strings is variable handling.

Heredoc

Another way to define strings is to use heredoc syntax. In this case, the line must begin with the character<<<, после которого идет идентификатор. Заканчивается строка этим же идентификатором. Закрывающий идентификатор должен начинаться в первом столбце строки. Кроме того, идентификатор должен соответствовать тем же правилам именования, что и все остальные метки в PHP: содержать только буквенно-цифровые символы и знак подчеркивания и начинаться не с цифры или знака подчеркивания.

Heredoc text behaves in the same way as a string in double quotes, without having them. This means that you don't need to escape quotes in heredoc, but you can still use the escape sequences listed above.

Variables inside heredoc are also processed.

$str =<<Example of a string spanning several
lines using
heredoc syntax
EOD;
// Here the identifier is EOD. Below
// EOT identifier
$name = "Vasya" ;
echo<<My name is "$name".
EOT;
// this will print "My name is "Vasya"."
?>

Example. Using heredoc syntax
Note: Heredoc support was added in PHP 4.

18. Type array

An array in PHP is an ordered map - a type that converts values ​​into keys. This type is optimized in several ways, so you can use it as an actual array, a list (vector), a hash table (which is a map implementation), a stack, a queue, etc. Because you can have another value as a value PHP array, Can
it's also easy to emulate trees.

You can define an array using the array() construct or by directly assigning values ​​to its elements. Definition using
array() array ( => value,
=> value1, ...)

The array() language construct takes key => value pairs as parameters, separated by commas. The => symbol matches a value with its key. The key can be either an integer or a string, and the value can be any type available in PHP. The numeric key of an array is often called the index. Array indexing in PHP starts from zero.

The value of an array element can be obtained by specifying the key of the element being searched after the array name in square brackets. If the array key is a standard integer notation, it is treated as a number; otherwise, it is treated as a string.

Therefore, writing $a["1"] is equivalent to writing $a, just as $a["-1"] is equivalent to $a[-1].

$books = array("php" =>
"PHP users guide" ,
12 => true );
echo $books [ "php" ];
//will display "PHP users guide"
echo $books [ 12 ]; //will output 1
?>

18.1. Example. Arrays in PHP

If a key is not specified for an element, then the maximum numeric key increased by one is taken as the key. If you specify a key that has already been assigned a value, it will be overwritten. As of PHP 4.3.0, if the maximum key is a negative number, then the next array key will be zero (0).

// arrays $arr and $arr1 are equivalent
$arr = array(5 => 43 , 32 , 56 , "b" => 12 );
$arr1 = array(5 => 43 , 6 => 32 ,
7 => 56 , "b" => 12 );
?>

18.2. Example. Arrays in PHP

If you use TRUE or FALSE as a key, then its value is converted to one and zero of type integer, respectively. If we use NULL, then instead of the key we will get an empty string. You can also use the empty string itself as a key, but it must be enclosed in quotes. So it's not the same as using empty ones square brackets. Arrays and objects cannot be used as keys.

Definition using square bracket syntax

You can create an array by simply writing values ​​into it. As we have already said, the value of an array element can be obtained using square brackets, inside which you need to indicate its key, for example, $book["php"]. If you specify a new key and a new value, for example, $book["new_key"]="new_value", then a new element will be added to the array. If we do not specify the key, but only assign the value $book="new_value", then the new array element will have a numeric key that is one greater than the maximum existing one. If the array we are adding values ​​to does not already exist, it will be created.

$books [ "key" ]= value ; // added to the array
// $books value
// value with key
$books = value1 ; /* added to the array
value value1 s
key 13, because
maximum key y
there were 12 of us */
?>

In order to change a specific array element, you simply need to assign a new value to it and its key. You cannot change an element's key, you can only delete an element (key/value pair) and add a new one. To remove an array element, you need to use the unset() function.

$books = array("php" =>
"PHP users guide" ,
12 => true );
$books =
"Book about Perl" ; // added element
// with key (index)
// 13 is equivalent
// $books =
// "Book about Perl";
$books["lisp"] =
123456 ; /* This adds a new one to the array

In some cases, it is necessary to execute code until the desired result is achieved. To do this, PHP provides while, for, and foreach loops.

While loop syntax in PHP

Syntax cyclewhile:

An example of using a while loop in PHP:

In the php while loop example above, the counter variable $i is first initialized to 0.

The condition of the while loop is $i< 10 . Это означает, что мы проверяем, меньше ли переменная, чем 10.

Everything that is enclosed in curly braces is the instructions (body) of the loop. They are repeated as long as the condition returns true . In the example above, $i is printed to the screen and then the counter variable is incremented by 1. This is important so that the loop condition will eventually fail. If the loop condition is always met, for example because you forgot to increment the counter variable $i , then the script will enter an infinite loop. Luckily, PHP will stop executing your script after a while.

You can make both the loop condition and the loop body as complex as you like. For example, use while inside while php, use php while to iterate through the array ( array ) or define more than one counter variable:

$min) ( echo "count1: $count1; count2: $count2
"; $ counter1 += 2; // Shorthand expression for $counter1 = $counter1 + 2; $counter2 -= 3; // Shorthand expression for $count2 = $count2-3; ) ?>

The example defines two variables: $ counter 1 and $ counter 2 . One variable is incremented by 2 and the other is decremented by 3. The while loop runs as long as both conditions are met $ count 1< $ max и $ count 2 >$min.

Effect of the break and continue keywords on a loop

Using the command break Can interrupt the execution of the while loop in PHP. Let's say we are looking for a specific user. Then you can go through all the users in a while loop. If we find the desired user, then stop the loop using keyword break.

A simple example of using the break keyword:

while ($count< $max) { if ($count == 10) { echo "Останавливаемся на числе 10"; break; } echo "$count,"; $counter += $increment; // увеличивает $count на значение $increment } ?>

This code iterates through the numbers in ascending order from 0 to $max = 30, adding the value of $increment to the variable $count, in other words the number 2. But if the variable $count is equal to 10, the following will happen: exiting the while loop php.

Keyword continue does not terminate the loop while in php is completely , but just skips the rest of the loop body. The example below demonstrates this:

while ($count< $max) { $counter += $increment; // увеличивает $payer на $increment if ($count >= 10 && $count<= 15) { echo "Число между 10 и 15
"; continue; )

echo "$count
"; } ?>

This loop starts at 0 and increments the counter up to $max. The $counter variable is always incremented by the value of the $increment variable. That is, it takes values ​​0, 2, 4, etc.

If the $count variable has a value between 10 and 15, the text and statement will be printed to the screen continue will skip other expressions in the body of the loop. As a result, we see that the numbers 10, 12 and 14 are not output.

do-while loop in PHP

Minor modification while is a do - while loop. In this case, the loop condition is checked only after its body has been executed. This means that the body of the loop will be executed at least once.

Do-while loop syntax:

Suppose we want to generate random number, which must be either between 0 and 10 or between 20 and 30. According to the definition of the function rand ( $ min, $max) , you can randomly generate a number between $min And $max:

10 && $random< 20) { $random = rand (0, 30); }

echo "Our random number: $random"; ?>

Using php loop dowhile, you can get the value of an expression without initializing the $random variable. The body of the loop is executed before the condition is tested. Then the example above would look like this:

10 && $random< 20);

echo "Our random number: $random"; ?>

For a beginner, the do-while loop can be a little confusing. If you don't fully understand its purpose, that's not a problem. Do-while loops are rarely used in practice.

It is often convenient to be able to terminate a loop early when certain conditions arise. The break operator provides this opportunity. It works with constructs such as: while, do while, for, foreach or switch.

The break statement can take an optional numeric argument that tells it how many nested structures to terminate. The default value of the numeric argument is 1, which terminates the current loop. If a switch statement is used in a loop, then break/break 1 only exits from the switch construct.

\n"; break 1; /* Exit only the switch construct. */ case 10: echo "Iteration 10; let's go out
\n"; break 2; /* Exit the switch construct and the while loop. */ ) ) // another example for ($bar1 = -4; $bar1< 7; $bar1++) { // проверка деления на ноль if ($bar1 == 0) { echo "Выполнение остановлено: деление на ноль невозможно."; break; } echo "50/$bar1 = ",50/$bar1,"
"; } ?>

Of course, sometimes you would prefer to simply skip one of the iterations of the loop rather than complete the loop, in which case this is done using the continue statement.

continue

To stop processing the current block of code in the body of the loop and move on to the next iteration, you can use the continue statement. It differs from the break operator in that it does not stop the loop, but simply moves to the next iteration.

The continue operator, like break, can take an optional numeric argument, which indicates at how many levels of nested loops the rest of the iteration will be skipped. The default value of the numeric argument is 1, which skips only the remainder of the current loop.

"; continue; ) echo "50/$bar1 = ",50/$bar1,"
"; } ?>

Please note that while the loop was running, the zero value of the $counter variable was skipped, but the loop continued with the next value.

goto

goto is an unconditional jump operator. It is used to jump to another section of program code. The place where you need to go in the program is indicated using a label (simple identifier), followed by a colon. To proceed, the desired label is placed after the goto statement.

A simple example of using the goto statement:

The goto statement has some limitations on its use. The target label must be in the same file and in the same context, which means you can't jump outside the boundaries of a function or method, and you can't jump inside one of them. You also cannot jump inside any loop or switch statement. But it can be used to escape from these constructs (from loops and switch statements). Typically the goto statement is used instead of multi-level break statements.

"; ) echo "after the loop - before the mark"; // the instruction will not be executed end: echo "After the mark"; ?>


Close