How to stop a loop PHP - 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!

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++;
}
}
?>

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

foreach step 5 steps forward in an array

How can I step forward 5 steps when using foreach to output an arrays value? So In this the put will be 1, 5
$array = ("1","2","3","4","5","6","7","8","9");
foreach ($array as &$value) {
echo $value; //Where do I tell it to move 5 paces forward?
echo "<br/ >";
}
If a foreach loop cannot be used, I'm willing to use something else. I don't think "while" or "for" can be used here?
$array = array("1","2","3","4","5","6","7","8","9");
for($i=0; $i<count($array); $i+=5) {
echo $array[$i];
echo "<br/ >";
}
I would use a while loop. Just set an index outside of the loop, and add 5 to it on each iteration of the loop. When the index is larger than the length of the list, terminate the loop.
A more compact way to express these instructions is a for loop:
for ($i=0; $i<count($array); $i = $i+5)
If it is not numerically indexed
$count = -1;
foreach ($array as &$value) {
$count++;
if ($count%4 != 0) continue;
echo "$value".PHP_EOL;
}

Looping through an explode() in php weird output

I'm getting a very weird results when trying to loop through a comma delimited list in PHP.
It sometimes only outputs a few of them and there seems no logical reason to why it doesn't loop through all of them, and I can't for the life of me figure out what's actually causing it.
My code is:
//pids = &pids=1,2,3,6,7,9
$pids = $_GET['pids'];
$photoIdArray = explode(",", $pids);
for($i = 0; $i <= count($photoIdArray); $i++) {
foreach($photoIdArray as $j){
if($i == $j){
echo "{$j}";
}
}
}
// result = 1236
This is just for testing so there is im not checking the inputs to prevent exploits and what not at the moment.
Any help would be appreciated.
Thanks!
Combining 2 loop for and foreach is overkill for something like this
Try using only foreach
$pids = "1,2,3,6,7,9";
$photoIdArray = explode(",", $pids);
foreach($photoIdArray as $value)
{
echo $value;
}
Output
123679
It is because you are looping through your values and check if $i is the same as the value. You should check
if ($photoIdArray[$i] == $j) {
instead of
if ($i == $j) {
This is the reason it didn't work, but you should still use Baba's method.
I agree with Dusan, Baba & Co., but to answer the actual question:
Nothing weird happens here. i loops from 0 to 6 (though the array has only indices 0..5), and you compare i with the VALUES of the array, which range from 1 to 9. Of course, only the values 1 to 6 are matched, because i never exceeds 6.
EDIT: Asad and Sietse were faster.

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

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?

Categories