Adding to the loop except the last php. PHP foreach loop: two ways to use it

I am writing this article for beginners who are just starting to study PHP. In this article I will tell you about all kinds of loops in PHP, since this article was not on my website. There were only, but, despite the general similarity, it’s still not the same. IN PHP There is 4 types of cycles.

  1. WHILE
  2. DO-WHILE
  3. FOREACH

Let's look at them in order and start with the most popular. loop in PHP(and not only in PHP) - This FOR loop. The syntax for this loop is as follows:

For(Expression_1; Expression_2; Expression_3) (
operators
}

Expression_1 carried out immediately and unconditionally, Expression_3 executed after each iteration of the loop. Expression_2 is a check to see if the loop needs to continue. If the result of the expression is true, then the next iteration of the loop begins, and if false, then the cycle stops working.

The next type of loop is WHILE. This is a simpler type of loops whose syntax is as follows:

While(Expression) (
operators
}

Bye Expression returns true, the loop will run, and as soon as it appears false, it stops working.

DO-WHILE Loop very similar to WHILE, but with one difference. The exit condition is checked after the iteration is executed, not before. Thus, this loop will always execute at least 1 once. And so DO-WHILE loop syntax:

Do(
operators
)while(Condition);

And finally, the last type of cycles is foreach, which serves only for iterating over arrays and objects. It is necessary when the keys of the array are not numbers (which can be easily iterated through the same FOR), and strings. FOREACH loop syntax next:

Foreach($array_or_object as $key => $value) (
operators
}

And finally, let's apply everything 4 types of loops in PHP for looping through arrays:

$list = array(5, 2, 3, 10, 12, 10);
$array = array("a" => 1, "x" => 10, "m" => -5);
for ($i = 0; $i< count($list); $i++) {
echo $list[$i]."; ";
}
echo "
";
$i = 0;
while ($i< count($list)) {
echo $list[$i]."; ";
$i++;
}
echo "
";
$i = 0;
do(
echo $list[$i]."; ";
$i++;
)while($i< count($list));
echo "
";
foreach ($array as $key => $value) (
echo "$key = $value; ";
}
?>

Any programmer must know all these cycles by heart, so if suddenly something is unclear, re-read it again, or ask a question in the comments, and I will try to answer.

Good day everyone. Alexey Gulynin is in touch. In the last article we looked at links in PHP. In this article I would like to talk about various loops in PHP. There are 4 types in total:

  • Iterative for loop
  • Loop with precondition
  • Loop with postcondition
  • foreach loop

Let's look at all the cycles using examples. Let there be such a task: for 10 elements you need to print the squares of the number.
1) Iterative for loop:

"; } ?>

You can use multiple conditions in this loop. Suppose you need to check if the element is equal to 6, then do not output anything else (we don’t know the break statement yet). You can write it like this:

"; } ?>

2) Loop with precondition:

"; $i++; ) ?>

In this case, the squares of the first 10 numbers will also be displayed. This loop is called a loop with a precondition because the condition is checked at the beginning, unlike the next loop.

3) Loop with postcondition:

"; $i++; ) while ($i<= 10) ?>

In this case, the condition is checked after the code block is executed, and this code block will be executed once in any case.

4) Foreach loop. This loop is designed to iterate through array values ​​and appeared only in the fourth version of the PHP language. An array is a set of keys, each of which corresponds to a value. Arrays will be discussed in more detail in the following articles. I recommend subscribing to updates so you don't miss out.
The syntax for this loop is as follows:

Foreach (array as $key=>$value) (statement block)

$key represents the key, $value - value. This construction does not change the original array. To be able to modify the original array, you must use a reference type:

Foreach (array as $key=>&$value) (statement block)

Let's use this loop to display the contents of all environment variables (the $_SERVER array):

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

Be sure to dial this example and see how everything works.

Very often a situation arises when it is necessary to interrupt the execution of a loop. To do this, you need to use the break construct. This construct has one optional parameter. By default, this parameter is 1, i.e. we interrupt the execution of the current loop. Let's look at this example: create 2 iterative loops from 1 to 5 and, if the number is equal to 5, then print the number. In this case, if we simply use break , then the number 5 will be printed 5 times. If we write break(2) , then only once:

"; break; //run the script and then write break(2); ) ) ) ?>

This operator is convenient to use for search loops. As soon as we found what we were looking for, we immediately complete the cycle.

The continue statement, on the contrary, skips the current iteration of the loop and moves on to the next one. You can also indicate the nesting level of the loop in parentheses.
I won’t give an example, I’ll give you homework on this operator.

It's unlikely that you can write a serious script in PHP without using loops. What is a cycle? This is a special type of control structure that allows you to repeatedly (and even endlessly) execute the same code. The following loops are supported in PHP:

The first three loops are the ones you'll most likely see in most programming languages. Loops, depending on the conditions, can be interrupted or continued (proceed to the next iteration without executing the body of the loop). Let's take a closer look at each of the cycles.

for loop

The syntax of the for loop is as follows.

For(initialization; condition; commands_after_iteration) (loop_body; )

The initialization block always initializes the counter, as well as other variables (if necessary). The condition block specifies at what point the loop should stop running. In the block of commands executed after each iteration of the loop, the value of the counter usually changes, as well as other variables (if necessary).

// Array of values ​​$array = array("Apple", "Potato", "Watermelon", "Flower", "Water", "Mercury", "Oxygen", "Wheat", "Russia", "Moscow", " Shower"); // The loop condition sounds like this: until the counter reaches a value equal to the number // of array elements, the body of the loop is executed for($i = 0; $i< count($array); $i++) { print "
".($i + 1)". ".$array[$i].."; ) /* The result of the cycle will be as follows: 1. Apple. 2. Potato. 3. Watermelon. 4. Flower. 5. Water. 6. Mercury. 7. Oxygen. 8. Wheat. 9. Russia. 10. Moscow.

Since the counter $i started from zero, at each iteration we added one to its value to make the list look more familiar. After each iteration, the counter value was incremented by one, and when it reached 11, the loop stopped. Now let's take a look at the do-while loop.

do-while loop

The do-while loop is different in that it operates on a postcondition. This means that the code contained in the body of the loop will be executed at least once. The loop syntax is:

Do (loop_body; ) while(condition);

This loop is used quite rarely in web programming, but you may need it in your scripts.

// Already familiar array to us $array = array("Apple", "Potato", "Watermelon", "Flower", "Water", "Mercury", "Oxygen", "Wheat", "Russia", "Moscow" , "Rain"); // Start the loop $i = 1; do(print"
".$i.". ".$array[($i - 1)]."; ) while($i++< count($array)); /* Результат работы цикла будет таким: 1. Яблоко. 2. Картошка. 3. Арбуз. 4. Цветок. 5. Вода. 6. Ртуть. 7. Кислород. 8. Пшеница. 9. Россия. 10. Москва. 11. Ливень. */

Notice the difference between what we print in this loop and the for loop. Since the code in the body of the do-while loop is executed at least once, the initial value of the counter was set to zero. How a loop works... code is executed, then a condition is tested. At the first iteration, the counter had a value of 1. After iteration, one turned out to be less than 11 (the number of elements). At the last iteration, the counter had a value of 11, and this is in no way less than 11. The cycle stopped. Very similar to do-while while loop.

while loop

The while loop is preconditional. It will only be executed when its condition is true. That is, the while loop may not be executed at all. Its syntax is:

While(condition) (loop_body; )

Along with the for loop, the while loop is used very often.

$array = array("Apple", "Potato", "Watermelon", "Flower", "Water", "Mercury", "Oxygen", "Wheat", "Russia", "Moscow", "Rain"); $i = 1; while($i++<= count($array)) { print "
".$i.". ".$array[($i - 1)]."."; ) /* The result of the loop will be as follows: 1. Apple. 2. Potato. 3. Watermelon. 4. Flower. 5. Water. 6. Mercury. 7. Oxygen. 8. Wheat. 9. Russia. 11. Rain.

The while loop is the simplest and most understandable for beginner developers.

foreach loop

The foreach loop is not like all of the above. It appeared in PHP4 and is designed to iterate over arrays. The developer does not need to invent anything for this. Everything is easy and simple:

/** * The foreach loop should be understood as "for each of". * The array processed by the loop is passed to a variable that is * accessible only inside the body of the loop. If desired, you can also access * array keys. */ foreach(array as array_element) (loop_body; ) foreach(array as array_key => array_element) (loop_body; )

The principle of the foreach loop is completely different from the for , while and do-while loops. Therefore, it is quite difficult for inexperienced developers to understand what exactly can (and even should) be done with it.

// Let's change the array we already know. Let's make it associative. $array = array("Apple" => "fruit", "Potato" => "vegetable", "Watermelon" => "berry", "Flower" => "plant", "Water" => "liquid", “Mercury” => “metal”, “Oxygen” => “gas”, “Wheat” => “bread”, “Russia” => “our Motherland”, “Moscow” => “the capital of our Motherland”, “Rain " => "popados"); $i = 1; // We can do this foreach($array as $v) ( print "
".$i.". ".$v."."; $i++; ) /* We get this unexpected result: 1. fruit. 2. vegetable. 3. berry. 4. plant. 5. liquid. 6. metal. 7. gas. 8. bread. 9. our Motherland. 10. capital of our Motherland. */ // Now let’s do it differently foreach($array as $k => $v) ( print "
".$i.". ".$k." is ".$v."; $i++; ) /* Now the result will be like this 1. An apple is a fruit. 2. A potato is a vegetable. 3. A watermelon is a berry. 4. A flower is a plant. 5 . Water is a liquid. 6. Mercury is a metal. 8. Wheat is a bread. 10. Moscow is the capital of our Motherland. . */

Do you understand how this cycle works? If not, you can ask a question in the comments to the material.

You can use constructs in any loop break or continue. Sometimes it doesn't make sense to continue the loop or you need to move on to the next iteration.

$array = array("Apple" => "fruit", "Potato" => "vegetable", "Watermelon" => "berry", "Flower" => "plant", "Water" => "liquid", “Mercury” => “metal”, “Oxygen” => “gas”, “Wheat” => “bread”, “Russia” => “our Motherland”, “Moscow” => “the capital of our Motherland”, “Rain " => "popados"); $i = 1; // An example of how a loop works with the construct continue foreach($array as $k => $v) ( if($k != "Oxygen") continue; print "
".$i.". ".$k." is ".$v."; $i++; ) /* The result will be like this 1. Oxygen is a gas. */ $i = 1; // An example of how a loop works with the construction break foreach($array as $k = > $v) ( if($k == "Oxygen") break; print "
".$i.". ".$k." is ".$v."; $i++; ) /* The result will be 1. An apple is a fruit. 2. A potato is a vegetable. 3. A watermelon is a berry. 4. A flower is a plant. 5. Water is a liquid. 6. Mercury is a metal.

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"; ?>

The PHP foreach loop can be used like this:

foreach($array_name as $value)( //code to be executed)

foreach($array_name as $key =>$value)( // //code that should be executed)

Example of using a foreach loop with a numeric array

In this example we will create an array of five elements with numerical values. The PHP foreach loop will then be used to iterate through this array. Inside the foreach loop we used echo to print out the array values:

View demo and code

Example with array keys and values

This example describes another way to use the PHP foreach loop. To do this, we created an associative array of three elements. It includes the names of employees ( as keys) and the amount of wages ( as values):

View demo and code

An example of changing the value of an array element in a foreach loop

You can also c using PHP array foreach can change the values ​​of array elements. To do this, use "&" before "$" for value variable. For example:

&$value_of_element

The value will be changed. To make it clearer, consider the following example.

In this example, we created a numeric array of five elements. After that, we used a foreach loop to display the values ​​of the elements.

Then we created another foreach loop, where "& " is added before $value_of_element. Inside the curly braces we assign new values ​​to the elements of the array.

To see the difference before and after assigning new values, the array is displayed using the print_r() function.

View demo and code

What is the PHP foreach loop used for?

The PHP foreach loop is used to work with an array. It iterates over each of its elements.

You can also use a for loop to work with arrays. For example, using the length property to get the length of an array and then applying it as the max operator. But foreach makes it easier since it is designed to work with arrays.

If you work with MySQL, then this cycle is even more suitable for this. For example, you can select several rows from a database table and pass them into an array. After that, using a foreach loop, iterate through all the elements of the array and perform some action.

Note that you can use a foreach loop with an array or just an object.

Using a foreach loop

There are two ways to use the PHP foreach loop in PHP. Both are described below.

  • The syntax for the first method is:

foreach($array_name as $value)( echo $value )

In this case, you need to specify the array name, and then the $value variable.

For each iteration, the value of the current element is assigned to the $value variable. After the iteration is completed, the variable is assigned the value of the next element. And so on until all the elements of the array have been iterated.

  • Syntax of the second method ( PHP foreach as key value):

This is suitable for associative arrays that use key/value pairs.

During each iteration, the value of the current element will be assigned to the $value_of_element variable. In addition, the element key is assigned to the $key_of_element variable.

If you are working with numeric arrays, you can use the first method, which does not require element keys.

This publication is a translation of the article “ PHP foreach loop 2 ways to use it", prepared by the friendly project team

Share