I have a php array $numbers = array(1,2,3,4,5,6,7,8,9)
if I am looping over it using a foreach foreach($numbers as $number)
and have an if statement if($number == 4)
what would the line of code be after that that would skip anything after that line and start the loop at 5? break, return, exit?
You are looking for the continue statement. Also useful is break which will exit the loop completely. Both statements work with all variations of loop, ie. for, foreach and while.
$numbers = array( 1, 2, 3, 4, 5, 6, 7, 8, 9 );
foreach( $numbers as $number ) {
if ( $number == 4 ) { continue; }
// ... snip
}
continue;
Continue will tell it to skip the current iteration block, but continue on with the rest of the loop. Works in all scenerios (for, while, etc.)
Break; will stop the loop and make compiler out side the loop. while continue; will just skip current one and go to next cycle.
like:
$i = 0;
while ($i++)
{
if ($i == 3)
{
continue;
}
if ($i == 5)
{
break;
}
echo $i . "\n";
}
Output:
1
2
4
6 <- this won't happen
I suppose you are looking for continue statement. Have a look at http://php.net/manual/en/control-structures.continue.php
dinel
Related
I have a do while loop and a nested foreach loop. And i'm using break 2 to break both(do while and foreach) if $x > N(in this case N = 4). For now it works but...is this a good practice? Or should i break the while loop in some other way?
$arr = ['a', 'b', 'c'];
$x = 0;
do{
//do something here...
//and something here...
foreach($arr as $k => $v){
if($x > 4){
break 2;
} else{
echo '(' . $x . ')' . $k . ' - ' . $v . '<br />';
}
}
$x++;
} while($x < 10);
Thank you! :D
Using a do{}while(); loop should be a very deliberate decision. Its behavior forces an initial iteration and only checks the break condition(s) at the end of each iteration.
Compare this to a while() loop or better for your purposes a for() loop. It performs the conditional check before each iteration AND the counter, the break condition(s), and the incrementation are all in one readable location.
I'm not sure if you actually mean to execute...
//do something here...
//and something here...
...on the same iteration where the break 2 occurs. What circumstance makes this suitable for your project? The logic of your snippet says, that you want to execute those mystery lines of code when $x = 0, 1, 2, 3, 4, and 5; but the foreach() block is only to be executed when $x = 0, 1, 2, 3, and 4.
If I am right that your design logic is slightly flawed then, I do not recommend writing a break point inside your loop with the other processes. I recommend a for() loop.
$arr = ['a', 'b', 'c'];
for ($x = 0; $x <= 4; ++$x) {
//do something here...
//and something here...
foreach ($arr as $k => $v){
echo "($x)$k - $v<br />";
}
}
Because of your break 2, your while($x < 10); condition will never be satisfied, so it is an illogical design inclusion.
If you DO, in fact, need to execute those mystery lines, but not the looped echoes when $x = 5, then relinquish loop control to the break entirely and use while(true) (writing an indefinite loop) to remove developer confusion.
$arr = ['a', 'b', 'c'];
$x = 0;
while (true) {
//do something here...
//and something here...
if ($x > 4) {
break 2;
}
foreach ($arr as $k => $v) {
echo "($x)$k - $v<br />";
}
++$x;
}
In your example break 2 will work fine and yes, it is part of PHP. However, I have always had a concern about breaking out of loops especially when these are nested.
Consider if you were working on code that was much more complex that that included nested loops. When you specified the break out of 2 loops, you would need to be very careful that you took account of the breaks in any new code.
So while using break may work, I always to try to avoid breaks and always consider if there is a different option that works without the need for breaks (especially when you have nested loops). In your example, I would use the code:
$arr = ['a', 'b', 'c'];
$x = 0;
do{
//do something here...
//and something here...
foreach($arr as $k => $v){
echo '(' . $x . ')' . $k . ' - ' . $v . '<br />';
}
$x++;
} while($x <= 4);
This usually leads to neater code that is easier to maintain.
This question already has answers here:
How does PHP 'foreach' actually work?
(7 answers)
Closed 4 years ago.
Php 'Continue' will tell it to skip the current iteration block, but continue on with the rest of the loop. Works in all scenerios (for, while, etc.).But I want to skip the rest of the loop.I tried it using break;But not work.
if ($column_names > 0) {
foreach ($column_names as $heading) {
foreach ($heading as $column_heading)
if($column_heading == "trip_id"){
break;
}
if($column_heading == "number_of_pessengers"){
$column_heading = "No. pessengers";
}
$cellWidth = $pdf->GetStringWidth($column_heading);
$pdf->Cell($cellWidth + 2, 10, $column_heading, 1);
}
}
What's the wrong in my code.
Try break 2;
If you want to exit out of nested loops you have to use the "argument" for break.
foreach ($column_names as $heading) {
foreach ($heading as $column_heading)
if($column_heading == "trip_id"){
break 2; //break out of both loops.
}
if($column_heading == "number_of_pessengers"){
$column_heading = "No. pessengers";
}
$cellWidth = $pdf->GetStringWidth($column_heading);
$pdf->Cell($cellWidth + 2, 10, $column_heading, 1);
}
}
Who knew you can put a number with break, also continue works the same way.
http://php.net/manual/en/control-structures.break.php
break ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.
Cheers
If you want to exist from both loop then you have to keep a flag variable
if ($column_names > 0) {
foreach ($column_names as $heading) {
$flag = 0;
foreach ($heading as $column_heading){
if($column_heading == "trip_id"){
$flag = 1;
break;
}
if($column_heading == "number_of_pessengers"){
$column_heading = "No. pessengers";
}
$cellWidth = $pdf->GetStringWidth($column_heading);
$pdf->Cell($cellWidth + 2, 10, $column_heading, 1);
}
if($flag == 1) break;
}
or you can use break 2;
you can check here How can I break an outer loop with PHP?
I'm having trouble understanding how the foreach loop works in this code. My understanding is that $Score is assigned the arrays of $Die1 + $Die2, but how does $Score gain the value of 1,2,3,4,5,6,5,4,3,2,1? Shouldn't it be 1,2,3,4,5,6,1,2,3,4,5,6 in a sequence since that's how the values are listed in the $FaceValues array? Is there something that's happening in the foreach statements that I'm missing? Can anyone could elaborate on the double foreach statements here?
$FaceValues = array(1, 2, 3, 4, 5, 6);
$ScoreCount = array();
for($PossibleRolls = 2; $PossibleRolls <= 12; ++$PossibleRolls){
$ScoreCount[$PossibleRolls] = 0;
}
foreach ($FaceValues as $Die1) {
foreach ($FaceValues as $Die2) {
// all possible combinations
++$RollCount;
// increment RollCount
$Score = $Die1 + $Die2;
// 1,2,3,4,5,6
// 6,5,4,3,2,1
++$ScoreCount[$Score];
}
}
foreach ($ScoreCount as $ScoreValue => $ScoreTimes){
echo "<p> A combined value of $ScoreValue occured $ScoreTimes of $RollCount times. </p>";
}
On the first iteration $Die1 is 1 and $Die2 is 2. So it begins at 2 and goes up to 7. Then the inner loop is finished and the outer loop proceeds to set $Die1 to 2. You should then see the number 3 through 8.
You can use echo or var_dump() and exit() to print the values at each step and stop if you're having trouble following-along.
problem Solved..... thanks alot
I want to break the loop and continue loop from the point that the loop stop. E.g., if I have array like this:
$arr = array('1', '2', '3', '4', '5');
I want to stop looping on number '3' and take an action and continue from '4'. I tried this code:
$x = 0;
foreach($arr as $key){
if($x == 3) break; // here I stop loop in number 3
echo $key;
$x++;
// I want to continue loop from 4
}
why stop?
use
$x = 0;
foreach($arr as $key){
if($x == 3)
doSomething();
else
echo $key;
$x++;
}
it will continue with iteration 4, after "doing Something". (Correctly spoken: It will iterate from 1 to n, and only perform an action, when $x==3, otherwhise print the key.)
If you just want to avoid key "3" beeing printed, you can use the continue statement:
$x = 0;
foreach($arr as $key){
if($x++ == 3)
continue; //proceed with next iteration
echo $key;
}
but then you need to use $x++ in your comparrision, otherwhise it will get stuck at $x==3, cause the increment will always be skipped.
Sidenode: If you NEED $x to be the correct line number, use a for() instead of foreach() - use foreach(), if you dont care about the actual line number, but need to process ALL entries within an array.
Sidenode 2: foreach($arr as $key) is wrong. This expression will give you the value for each array entry, not the key. use foreach($arr as $key=>$value) or foreach($arr as $value) to have a correct name on the variable(s).
I try to create a list with nested foreach loop. First loop is looping some numbers, second loop is looping dates. I want to write one number to one date. So there is a another function to check that. But the result is numbers writes on dates multiple times.
Out is something like that :
number 5 is on 2013.01.15;
number 5 is on 2013.01.16;
number 5 is on 2013.01.17;
number 6 is on 2013.01.15;
number 6 is on 2013.01.17;
The code :
function create_event($numbers,$available_dates) {
foreach($numbers as $number) {
foreach($avaliable_dates as $av_date) {
$date_check= dateCheck($av_date,$number);
if ($date_check == 0) {
echo "number ".$number." is on ".$av_date;
break;
} else {
$send_again[] = $number;
}
}
}
create_event($send_again,$avaliable_dates);
}
I think inside loop is not break.
Your break; should break inner foreach loop!
The only reason for such behavior I see is repeating numbers in you array!(E.g. $numers=array(5,5,5,6,6); )
Try to insert: $numbers=array_unique($numbers); before your outer foreach loop
If you need to break both loops(inner and outer) write break 2; instead of break;
Can you check something like this:
function create_event($numbers,$available_dates) {
foreach ($numbers as $number) {
foreach ($available_dates as &$av_date) {
if (dateCheck($av_date, $number) == 0) {
unset($av_date);
break;
}
}
}
}