Stop loop and continue from stopping point - php

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

Related

How does this foreach loop code work in 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.

Know the count of for-each loop before executing that loop

How may i know that - In php how many times the foreach loop will get run, before that loop get executed..In other words i want to know the count of that particular loop. I want to apply some different css depends upon the count.
Use the function count to get the amount of numbers in your array.
Example:
$array = array('test1', 'test2');
echo count($array); // Echos '2'
Or if you want to be an engineer for-sorts you can set up something like so:
$array = array('test1', 'test2');
$count = 0;
foreach ($array as $a) { $count++; }
And that can count it for you, and the $count variable will hold the count, hope this helped you.
Simply count() the array and use the output as a condition, like:
if (count($array) > 100) {
// This is an array with more than 100 items, go for plan A
$class = 'large';
} else {
// This is an array with less than 100 items, go for plan B
$class = 'small';
}
foreach ($array as $key => $value) {
echo sprintf('<div id="%s" class="%s">%s</div>', $key, $class, $value);
}

Repeat ForEach Loop (PHP) But Break [duplicate]

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

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!

how to skip elements in foreach loop

I want to skip some records in a foreach loop.
For example, there are 68 records in the loop. How can I skip 20 records and start from record #21?
Five solutions come to mind:
Double addressing via array_keys
The problem with for loops is that the keys may be strings or not continues numbers therefore you must use "double addressing" (or "table lookup", call it whatever you want) and access the array via an array of it's keys.
// Initialize 25 items
$array = range( 1, 25, 1);
// You need to get array keys because it may be associative array
// Or it it will contain keys 0,1,2,5,6...
// If you have indexes staring from zero and continuous (eg. from db->fetch_all)
// you can just omit this
$keys = array_keys($array);
for( $i = 21; $i < 25; $i++){
echo $array[ $keys[ $i]] . "\n";
// echo $array[$i] . "\n"; // with continuous numeric keys
}
Skipping records with foreach
I don't believe that this is a good way to do this (except the case that you have LARGE arrays and slicing it or generating array of keys would use large amount of memory, which 68 is definitively not), but maybe it'll work: :)
$i = 0;
foreach( $array as $key => $item){
if( $i++ < 21){
continue;
}
echo $item . "\n";
}
Using array slice to get sub part or array
Just get piece of array and use it in normal foreach loop.
$sub = array_slice( $array, 21, null, true);
foreach( $sub as $key => $item){
echo $item . "\n";
}
Using next()
If you could set up internal array pointer to 21 (let's say in previous foreach loop with break inside, $array[21] doesn't work, I've checked :P) you could do this (won't work if data in array === false):
while( ($row = next( $array)) !== false){
echo $row;
}
btw: I like hakre's answer most.
Using ArrayIterator
Probably studying documentation is the best comment for this one.
// Initialize array iterator
$obj = new ArrayIterator( $array);
$obj->seek(21); // Set to right position
while( $obj->valid()){ // Whether we do have valid offset right now
echo $obj->current() . "\n";
$obj->next(); // Switch to next object
}
$i = 0;
foreach ($query)
{
if ($i++ < 20) continue;
/* php code to execute if record 21+ */
}
if want to skipped some index then make an array with skipped index and check by in_array function inside the foreach loop if match then it will be skip.
Example:
//you have an array like that
$data = array(
'1' => 'Hello world',
'2' => 'Hello world2',
'3' => 'Hello world3',
'4' => 'Hello world4',
'5' => 'Hello world5',// you want to skip this
'6' => 'Hello world6',// you want to skip this
'7' => 'Hello world7',
'8' => 'Hello world8',
'9' => 'Hello world8',
'10' => 'Hello world8',//you want to skip this
);
//Ok Now wi make an array which contain the index wich have to skipped
$skipped = array('5', '6', '10');
foreach($data as $key => $value){
if(in_array($key, $skipped)){
continue;
}
//do your stuf
}
You have not told what "records" actually is, so as I don't know, I assume there is a RecordIterator available (if not, it is likely that there is some other fitting iterator available):
$recordsIterator = new RecordIterator($records);
$limited = new LimitIterator($recordsIterator, 20);
foreach($limited as $record)
{
...
}
The answer here is to use foreach with a LimitIterator.
See as well: How to start a foreach loop at a specific index in PHP
I'm not sure why you would be using a foreach for this goal, and without your code it's hard to say whether this is the best approach. But, assuming there is a good reason to use it, here's the smallest version I can think of off the top of my head:
$count = 0;
foreach( $someArray as $index => $value ){
if( $count++ < 20 ){
continue;
}
// rest of foreach loop goes here
}
The continue causes the foreach to skip back to the beginning and move on to the next element in the array. It's extremely useful for disregarding parts of an array which you don't want to be processed in a foreach loop.
for($i = 20; $i <= 68; $i++){
//do stuff
}
This is better than a foreach loop because it only loops over the elements you want.
Ask if you have any questions
array.forEach(function(element,index){
if(index >= 21){
//Do Something
}
});
Element would be the current value of index.
Index increases with each turn through the loop.
IE 0,1,2,3,4,5;
array[index];

Categories