Break 2 php что это

# Loops

Loops are a fundamental aspect of programming. They allow programmers to create code that repeats for some given number of repetitions, or iterations. The number of iterations can be explicit (6 iterations, for example), or continue until some condition is met (‘until Hell freezes over’).

This topic covers the different types of loops, their associated control statements, and their potential applications in PHP.

# continue

The continue keyword halts the current iteration of a loop but does not terminate the loop.

Just like the break statement the continue statement is situated inside the loop body. When executed, the continue statement causes execution to immediately jump to the loop conditional.

In the following example loop prints out a message based on the values in an array, but skips a specified value.

$list = ['apple', 'banana', 'cherry']; foreach ($list as $value)  if ($value == 'banana')  continue; > echo "I love to eat $value> pie.".PHP_EOL; > 
I love to eat apple pie. I love to eat cherry pie. 

The continue statement may also be used to immediately continue execution to an outer level of a loop by specifying the number of loop levels to jump. For example, consider data such as

Fruit Color Cost
Apple Red 1
Banana Yellow 7
Cherry Red 2
Grape Green 4

In order to only make pies from fruit which cost less than 5

$data = [ [ "Fruit" => "Apple", "Color" => "Red", "Cost" => 1 ], [ "Fruit" => "Banana", "Color" => "Yellow", "Cost" => 7 ], [ "Fruit" => "Cherry", "Color" => "Red", "Cost" => 2 ], [ "Fruit" => "Grape", "Color" => "Green", "Cost" => 4 ] ]; foreach($data as $fruit)  foreach($fruit as $key => $value)  if ($key == "Cost" && $value >= 5)  continue 2; > /* make a pie */ > > 

When the continue 2 statement is executed, execution immediately jumps back to $data as $fruit continuing the outer loop and skipping all other code (including the conditional in the inner loop.

# break

The break keyword immediately terminates the current loop.

Similar to the continue statement, a break halts execution of a loop. Unlike a continue statement, however, break causes the immediate termination of the loop and does not execute the conditional statement again.

$i = 5; while(true)  echo 120/$i.PHP_EOL; $i -= 1; if ($i == 0)  break; > > 

but will not execute the case where $i is 0, which would result in a fatal error due to division by 0.

The break statement may also be used to break out of several levels of loops. Such behavior is very useful when executing nested loops. For example, to copy an array of strings into an output string, removing any # symbols, until the output string is exactly 160 characters

$output = ""; $inputs = array( "#soblessed #throwbackthursday", "happy tuesday", "#nofilter", /* more inputs */ ); foreach($inputs as $input)  for($i = 0; $i  strlen($input); $i += 1)  if ($input[$i] == '#') continue; $output .= $input[$i]; if (strlen($output) == 160) break 2; > $output .= ' '; > 

The break 2 command immediately terminates execution of both the inner and outer loops.

# foreach

The foreach statement is used to loop through arrays.

For each iteration the value of the current array element is assigned to $value variable and the array pointer is moved by one and in the next iteration next element will be processed.

The following example displays the items in the array assigned.

$list = ['apple', 'banana', 'cherry']; foreach ($list as $value)  echo "I love to eat $value>. "; > 
I love to eat apple. I love to eat banana. I love to eat cherry. 

You can also access the key / index of a value using foreach:

foreach ($list as $key => $value)  echo $key . ":" . $value . " "; > //Outputs - 0:apple 1:banana 2:cherry 

By default $value is a copy of the value in $list , so changes made inside the loop will not be reflected in $list afterwards.

foreach ($list as $value)  $value = $value . " pie"; > echo $list[0]; // Outputs "apple" 

To modify the array within the foreach loop, use the & operator to assign $value by reference. It’s important to unset the variable afterwards so that reusing $value elsewhere doesn’t overwrite the array.

foreach ($list as &$value)  // Or foreach ($list as $key => &$value) $value = $value . " pie"; > unset($value); echo $list[0]; // Outputs "apple pie" 

You can also modify the array items within the foreach loop by referencing the array key of the current item.

foreach ($list as $key => $value)  $list[$key] = $value . " pie"; > echo $list[0]; // Outputs "apple pie" 

# do. while

The do. while statement will execute a block of code at least once — it then will repeat the loop as long as a condition is true.

The following example will increment the value of $i at least once, and it will continue incrementing the variable $i as long as it has a value of less than 25;

$i = 0; do  $i++; > while($i  25); echo 'The final value of i is: ', $i; 
The final value of i is: 25 

# for

The for statement is used when you know how many times you want to execute a statement or a block of statements.

The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i .

The following example iterates 10 times and displays numbers from 0 to 9.

for ($i = 0; $i  9; $i++)  echo $i, ','; > # Example 2 for ($i = 0; ; $i++)  if ($i > 9)  break; > echo $i, ','; > # Example 3 $i = 0; for (; ; )  if ($i > 9)  break; > echo $i, ','; $i++; > # Example 4 for ($i = 0, $j = 0; $i  9; $j += $i, print $i. ',', $i++); 

# while

The while statement will execute a block of code if and as long as a test expression is true.

If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

The following example iterates till the sum reaches 100 before terminating.

$i = true; $sum = 0; while ($i)  if ($sum === 100)  $i = false; > else  $sum += 10; > > echo 'The sum is: ', $sum; 

# Syntax

# Remarks

It is often useful to execute the same or similar block of code several times. Instead of copy-pasting almost equal statements loops provide a mechanism for executing code a specific number of times and walking over data structures. PHP supports the following four types of loops:

To control these loops, continue and break statements are available.

Источник

Использование циклов в PHP

PHP имеет четыре вида циклов и операторы управления ими, рассмотрим поподробнее.

Foreach – перебор массива

Предназначен для перебора элементов массива.

Foreach – перебор массива

$array = array( 1 => 'Значение 1', 2 => 'Значение 2', 3 => 'Значение 3', 4 => 'Значение 4', ); // Вывод ключей foreach ($array as $key => $val) < echo $key . '
'; > // Вывод значений foreach ($array as $key => $val) < echo $val . '
'; >

Результат:

1 2 3 4 Значение 1 Значение 2 Значение 3 Значение 4

Альтернативный синтаксис foreach

For – цикл с счетчиком

Цикл работает пока выполняется заданное условие. Обычно применяется в качестве счетчика.

For – цикл с счетчиком

// Счетчик от 0 до 5 for ($n = 0; $n // Счетчик от 5 до 0 for ($n = 5; $n >= 0; $n--)

Результат:

Альтернативный синтаксис

$array = array( 'Значение 1', 'Значение 2', 'Значение 3', 'Значение 4', ); for ($n = 0; $n < count($array); $n++) < echo $array[$n] . '
'; >

Результат:

Значение 1 Значение 2 Значение 3 Значение 4

Альтернативный синтаксис for

While – цикл с предусловием

Т.е. если перед началом итерации условие выполняется, то цикл продолжает свою работу.

While – цикл с предусловием

Результат:

Альтернативный синтаксис while

Do-while – цикл с постусловием

В отличии от while этот цикл проверяет выполнения условия после каждой итерации. Do-while не имеет альтернативного синтаксиса.

Do-while – цикл с постусловием

Результат:

Управление циклами

Break

Вызов break или break 1 в цикле останавливает его.

Для вложенных циклов используется break 2 и т.д.

Continue

Используется для пропуска итерации.

Результат:

Для вложенных циклов по аналогии с break 2 , break 3 – continue 2 , continue 3 .

Источник

How to Break the nested loop in PHP

The break statement in PHP is utilized to terminate the execution of the current loop or switch case statement. However, when dealing with nested loops and the intention is to exit from one or more of the outer loops, you can achieve this by providing a numeric value with the break statement.

This tutorial demonstrates the process of terminating a specified number of nested foreach, for, while, and do-while loops in PHP by utilizing the break statement.

How to Break the nested loop in PHP

Table of Content

1. Break 2 foreach, for, while, and do-while loops

The break statement takes an optional numeric value its default value is 1 . This represents the number of loops to terminate.

For out from two inner loops pass 2 with a break statement from your inner loop when the particular condition is TRUE.

Break 2 foreach loop Example –

In the example, read $users Array data using 2 foreach loop. To exit from 2 foreach loop use break 2 if mentioned condition returns true.

"Yogesh", "age"=>30, "gender"=>"Male"); $users[] = array("name"=>"Sonarika","age"=> 29, "gender"=>"Female"); $users[] = array("name"=>"Anil", "age"=>19, "gender"=>"Male"); $users[] = array("name"=>"Vishal", "age"=>21, "gender"=>"Male"); foreach ($users as $user) < foreach ($user as $detail) < echo "value : ".$detail."
"; if($detail == 'Sonarika') < echo "-- break foreach --"; break 2; >> >
value : Yogesh value : 30 value : Male value : Sonarika -- break foreach --

Break 2 for loop Example –

Similarly, use break 2; statement to terminate 2 for loops.

Break 2 while loop Example –

num1 : 0, num2 : 0 num1 : 0, num2 : 1 num1 : 0, num2 : 2 num1 : 0, num2 : 3 num1 : 0, num2 : 4 num1 : 1, num2 : 0 num1 : 1, num2 : 1 num1 : 1, num2 : 2 num1 : 1, num2 : 3 num1 : 1, num2 : 4 num1 : 2, num2 : 0 num1 : 2, num2 : 1 num1 : 2, num2 : 2 num1 : 2, num2 : 3 -- break while loop --

Break 2 do-while loop Example –

"; if($num1 == 2 && $num2 == 3) < echo "-- break do while loop --"; break 2; >$num2++; > while ($num2 < 5); $num1++; >while ($num1 < 5);
num1 : 0, num2 : 0 num1 : 0, num2 : 1 num1 : 0, num2 : 2 num1 : 0, num2 : 3 num1 : 0, num2 : 4 num1 : 1, num2 : 0 num1 : 1, num2 : 1 num1 : 1, num2 : 2 num1 : 1, num2 : 3 num1 : 1, num2 : 4 num1 : 2, num2 : 0 num1 : 2, num2 : 1 num1 : 2, num2 : 2 num1 : 2, num2 : 3 -- break do while loop --

2. Break n number of nested foreach, for, while, and do-while loops

Same as above you can break any number of loops from your inner loop.

Here, n is the number of outer loops you want to break.

Break n number foreach loop Example –

In the example, using 3 foreach loop to read $usersList Array data. To exit from the 3 foreach loop use break 3; statement. Here, 3 is the number of loop that needs to break.

"; print_r($user); echo "

"; echo "-- Break 3 foreach loop --"; break 3; > > > >

Array ( [0] => Aditya [1] => 28 [2] => Male ) -- Break 3 foreach loop --

Break n number for loop Example –

In this example using 4 for loops and to break from the 4th loop use break 4; statement.

Break n number while loop Example –

 $a++; > $k++; $a = 0; > $j++; $k = 0; > $i++; $j = 0; > echo 'i = ' . $i;

Break n number do-while loop Example –

 $a++; > while ($a < 4); $k++; >while ($k < 3); $j++; >while ($j < 3); $i++; >while ($i < 5); echo 'i = ' . $i;

3. Conclusion

If you have a nested loop in your program, you can utilize the break statement to terminate a loop when a specified condition becomes TRUE.

To terminate­ a specified number of loops, all that is re­quired is to include an intege­r value along with the break state­ment.

If you found this tutorial helpful then don't forget to share.

Источник

Читайте также:  Php fpm d www config
Оцените статью