PHP, continue; on foreach(){ foreach(){ - php

Is there a way to continue on external foreach in case that the internal foreach meet some statement ?
In example
foreach($c as $v)
{
foreach($v as $j)
{
if($j = 1)
{
continue; // But not the internal foreach. the external;
}
}
}

Try this, should work:
continue 2;
From the PHP Manual:
Continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.
here in the examples (2nd exactly) described code you need

Try this: continue 2; According to manual:
continue accepts an optional numeric argument which tells it how many levels of enclosing loops it should skip to the end of.

There are two solutions available for this situation, either use break or continue 2. Note that when using break to break out of the internal loop any code after the inner loop will still be executed.
foreach($c as $v)
{
foreach($v as $j)
{
if($j = 1)
{
break;
}
}
echo "This line will be printed";
}
The other solution is to use continue followed with how many levels back to continue from.
foreach($c as $v)
{
foreach($v as $j)
{
if($j = 1)
{
continue 2;
}
}
// This code will not be reached.
}

This will continue to levels above (so the outer foreach)
continue 2

<?php
foreach($c as $v)
{
foreach($v as $j)
{
if($j = 1)
{
continue 2; // note the number 2
}
}
}
?>
RTM

Try break instead of continue.
You can follow break with an integer, giving the number of loops to break out of.

you have to use break instead of continue, if I get you right
Here I wrote an explanation on the matter: What is meant by a number after "break" or "continue" in PHP?

Related

echo a number in php

I am trying to learn php, and I am playing around with while loops. I was wondering how to print out a specific number in an array in php. Fx:
$a = [1,3,5,7,9,11,13];
$s = 3;
while($a == 3) {
echo $s.' is in the row';
$a++;
}
In this example I would like to run through the $a and see if 3 exist there. If it does it has to echo '3 is in the row' I tried to make a while loop, but it is not correct. Can anyone see what I am doing wrong? Just to say it, I think it is very wrong, but I don't know how to solve it, if I have to use the while loop?
Best Regards
Mads
Your while condition reads: "While the value of $a equals 3", but $a is an array, so its value can't ever be 3. The loop will never be executed. In PHP, we would write:
if (in_array($s, $a))
echo $s, ' was found in the array';
Or, if you insist on writing loops:
foreach ($a as $key => $value)
{
if ($value == $s)
{
echo $s, ' was found at offset ', $key;
break;//end terminate loop
}
}
Of course, you could also write:
for ($i=0, $j=count($a);$i<$j;++$j)
{
if ($a[$i] == $s)
{//you could move this condition to the loop itself, even
echo $s, ' found in array at offset ', $i;
break;
}
}
You can, if you want use a while loop, too, but that wouldn't be the best choice for your particular case. Just read through the manual on php.net. There are many, many array_* functions available, and there are many ways to iterate over your data.
Another worry is your using the array name as a sort-of C-style pointer: $a++; in C, an pointer can be incremented to set it to point to the next value in an array (if the new memory address is valid, and the pointer is valid, and all of the other things you have to worry about in C). PHP does not work this way. An array isn't really an array: it's a hash map. incrementing an array, therefore, is pointless and most likely to be a bug. The for loop is the closest you can get to traversing an array using the ++ operator.
You're looking for in_array. This checks if a value exists in an array, in the form of:
in_array ( mixed $needle , array $haystack )
So, in your case, you'd want to do:
$a = [1,3,5,7,9,11,13];
$s = 3;
if (in_array($s, $a)) {
echo $s.' is in the row';
}
foreach($a as $b) {
if($b == 3)
echo $b.' is in the row';
}
Modify slightly your code changing while condition:
$a = array(1,3,5,7,9,11,13);
$s = 3;
$counter = 0;
while($counter < count($a)) {
if ( $a[$counter] == $s )
echo $s.' is in the row';
$counter++;
}
Added counter to iterate through while loop until end of array.
count() method returns number of items in array.
This solution prints all occurences of your number.
To have better code, change names of variables:
$numbers = array(1,3,5,7,9,11,13);
$target = 3;
$counter = 0;
while($counter < count($numbers)) {
if ( $numbers[$counter] == $target )
echo $target.' is in the row';
$counter++;
}
There are two ways to do it,
First, you can loop through all items in the array using a foreach() loop.
That way, you can go through them all and if you have multiple conditions, it makes your code a bit more readable.
And example of that loop is like this:
foreach($array as $array_item) {
if($array_item === 3) {
echo "3 is in the array";
}
}
The alternative is to use a built in function to find if something is in the array. THis is probably much faster, though I haven't benchmarked the difference.
if(in_array(3, $array)) {
echo "3 is in the array";
}
you can use
array_search ,in_array , and forearch or for loops to itertate through the array.
For learning purposes
$a = [1,3,5,7,9,11,13];
$s = 3;
for($i=0;$i<count($a);$i++)
{
if($a[$i]==$s){
echo $s.' is in the row';
}
}
of course in real life
if (in_array(3, $a)) {
// Do something
}
would be better;
<?php
$a = [1,3,5,7,9,11,13];
$s = 3;
for($a=0;$a < 20; $a++)
{
while($a == 3) {
echo $s.' is in the row';
//$a++;
}
}
?>

Strange behavior of unset in foreach by reference loop

I know one should not modify physical structure of array while looping by reference, but I need explanation of what is going on in my code. Here we go:
$x= [[0],[1],[2],[3],[4]];
foreach ($x as $i => &$upper) {
print $i;
foreach ($x as $j => &$lower) {
if($i == 0 && $j == 2) {
unset($x[2]);
} else if($i == 1 && $j == 3) {
unset($x[3]);
}
}
}
The output is 01. Surprising that outer loop iterates only twice, for indices 0 and 1. I was expecting the output to be 014.
I have read lots of blog posts and questions about hazards of using array references, but nothing that can explain this phenomenon. I am breaking my head over it for hours now.
EDIT:
The code above is the minimal reproducible code. One explanation (but an incorrect one) that might seem to be the case is this:
The outer loop goes through two iterations before the internal pointer is set to index 2. But the loop does not find any element at index 2 and thus thinks no elements are left and quits.
The problem with this theory is it doesn't quite explain this code:
$x= [[0],[1],[2],[3],[4]];
foreach ($x as $i => &$upper) {
print $i;
foreach ($x as $j => &$lower) {
if($i == 0 && $j == 2) {
unset($x[2]);
// No if else here
unset($x[3]);
}
}
}
By the same token, the above code should also produce 01, but its actual output is 014, as expected. Even when two items in a series are removed, php knows that are still elements left to be iterated over. Could this possibly be a bug with php scripting engine?
A simple code to reproduce your issue:
$x = [0, 1, 2];
foreach ($x as $k => &$v) {
print $k;
if ($k == 0) {
unset($x[1]);
}
end($x); // move IAP to end
next($x); // move IAP past end (that's the same as foreach ($x as $y) {} would do)
}
If you foreach over an array, it's copied (= no problem when iterating, you'll iterate over the full original array).
But if you foreach by reference, the array is not copied (the reference needs to match the original array, so copying impossible).
Foreach internally always saves the position of the next element to iterate over.
But when the next position of an array is removed, foreach needs to go back to the array and check it's internal array pointer (IAP).
In this case the next position is destroyed and the IAP is past the end, it ends the loop.
That's what you're seeing here.
Also interesting: hhvm has a different behaviour to php here: http://3v4l.org/81rl8
Addendum: The infinite foreach loop:
$x = [0,1,2];
foreach ($x as $k => &$v) {
print $k;
if ($k == 1) {
unset($x[2]);
} else {
$x[2] = 1;
}
reset($x);
}
If you understood my explanations above, guess why that loops indefinitely.

Stop loop and continue from stopping point

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).

How to stop a loop PHP

I'm trying to figure out if its possible to stop a foreach loop in PHP, like this,
$arr = array('Joe', 'Jude', 'James', 'Pitch', 'Tim');
$i=0;
foreach($arr as $val){
echo $val;
if($i == 2){
//Stop looping
}
}
Is there anyway how to do that, if yes how do I that?
Thank you.
Use break and increment $i.
$arr = array('Joe', 'Jude', 'James', 'Pitch', 'Tim');
$i=0;
foreach($arr as $val){
echo $val;
if(++$i == 2){
break;
}
}
You can use good old keyword break here as well. Followed by a semicolon ; of course.
if($i == 2){
break;
}
Manual for break
You can break out of a loop with break.
1)As said earlier u need to increment the loop.
2)...if ur using multiple "foreach" that are nested,you can do break 'n' to get out of n nested loop,where n will specify any number from 1 to the total number of loops that you have used.Hope it helps!

Break levels in PHP

I have this snippet of code and it's working just fine (because in my example that variable really exists in $arrival_time so it breaks at about $k = 10).
$arrival_time = explode(",", $arrival_timeAll[1]);
$sizeOfArrival = sizeof($arrival_time);
$k = -1;
while (++$k < $sizeOfArrival) {
if ($arrival_time[$k] >= $someVariable) {
break;
}
}
Isn't that the same as this code? I added the while(true) loop and increased the "break level" - so it's now break 2, not just break. But seems that's an infinite loop. Why?
while (true) {
$arrival_time = explode(",", $arrival_timeAll[1]);
$sizeOfArrival = sizeof($arrival_time);
$k = -1;
while (++$k < $sizeOfArrival) {
if ($arrival_time[$k] >= $someVariable) {
break 2;
}
}
}
Why adding while(true)? Because I need to define some more statements (which here aren't neccesary for explanation) if inside while loop doesn't find the matching one (if that "break" in first case, "break 2" in second case doesn't run).
Anyway - why this isn't working?
In some cases, the predicate for the inner while loop is never hit, thus the while loop is never executed. As you don't have a break after it, the loop will run forever. This case would be if the array is empty, 0 < 0 is false.
Starting with $k = -1, the first time the predicate gets evaluated, $k will be 0 as you are using the preincrement operator, for an empty array this will evaluate to false and the code with run infinite. Without the while(true) loop this wouldn't cause any problems as you'd just jump straight over it.

Categories