Step inside foreach - php

How to do something every 5 (for example) cycles inside foreach?
I'm add $i++ How to check it by step?

Use modulo to determine offset.
$i = 0;
foreach ($array as $a) {
$i++;
if ($i % 5 == 0) {
// your code for every 5th item
}
// your inside loop code
}

Unless you're doing something separately in each iteration, don't.
Use a for loop and increment the counter by 5 each time:
$collectionLength = count($collection);
for($i = 0; $i < $collectionLength; i+=5)
{
// Do something
}
Otherwise, you can use the modulo operator to determine if you're on one of the fifth iterations:
if(($i + 1) % 5 == 0) // assuming i starts at 0
{
// Do something special this time
}

for($i = 0; $i < $items; $i++){
//for every 5th item, assuming i starts at 0 (skip)
if($i % 5 == 0 && $i != 0){
//execute your code
}
}

Related

PHP even numbers generating

I'm somewhat new to PHP, been reading a few books and I've never seen a loop where it gets you all the even numbers(for example from 1 to 10), so I decided to try it myself:
for($i=0;$i<10 && $i % 2===0;$i++)
echo $i;
Tried with only double == as well.
And this,
$i=0;
do echo $i; while($i++<10 && $i % 2 ==0);
Can't seem to figure out how to use 2 conditions in the same statement.
Would appreciate the help!
Thanks.
Try to use this code
for( $i=0; $i<=10; $i++ )
{
if( $i%2 == 0 ){
echo $i;
}
}
The loop is breaking entirely when the second condition fails the first time. On the first iteration: 0 is less than 10, and it is even, so the loop iterates. On the second iteration: 1 is less than 10, but is odd, so the loop breaks.
Your code is the equivalent of this:
for($i=0; $i<10; $i++) {
if ($i % 2 !==0 ) {
break;
}
echo $i;
}
0
You can eliminate the second condition of your for loop to prevent the breakage and rely exclusive on a third expression to increment $i by two each iteration.
for($i=0; $i<10; $i = $i + 2) {
echo $i;
}
02468
The second statement in a for-loop is/are the condition(s) which gets checked every loop. so if it fails your loop stops. what you need will look somewhat like this:
for ($i = 0; $i < 10; $i++)
if ($i % 2 == 0)
echo $i;
So the loop will run over every number but only print out the even ones.
You don't need to loop.
Range can create a range with third parameter step 2.
$arr = range(0,20,2);
Echo implode(" ", $arr);
https://3v4l.org/S3JWV
you can use also regular loop and get the evens by formula:
for($i=0; $i<10 ;$i++) {
$j = $i * 2;
// do somthing with $j witch loop over 10 first evens...
}

forloop continue again after end of the iteration

I used function with same logic given below
Given below code is sample of same logic i used, i need to continue the for loop after end of the iteration, i assign 0 to the variable $j at end so forloop need to continue, why its closed the process.
for($i=$j;$i<7;$i++){
echo "<br/>".$i;
if($i == 6){$j=0;continue;}
}
Actual Output
1
2
3
4
5
6
Expected output
1
2
3
4
5
6
1
2
3
4
5
6
.....etc
My Original code sample is
foreach($Qry_Rst as $key=>$Rst_Val){
for($j=$ItrDt;$j<7;$j++){
$ItrDate = date('Y-m-d', mktime(0, 0, 0, $month, $day + $j, $year));
if($ItrDate == $Rst_Val['sloat_day']){
$TimeTableAry[$loop_itr] = $Rst_Val;
break
}
}
}
The doc says
The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.
So instead of $j just use $i to reset the loop. As this (demo)
$j = 1;
$current = 0;
for ($i=$j; $i<4; $i++) {
printf("i: %d, j: %d\n", $i, $j);
if ($i==3 && $current < 5) {
$i = -1;
$j = mt_rand(0,3);
$current++;
continue;
}
}
shows, you actually need to reset $i = -1; so it will be 0 after $i++ will be evaluated.
But with this you'll have an if in every iteration of the loop although you only need it for one. Basically you don't need it for the iteration itself but only to start a next one, so there must be something else here.
function doFor($data, $callback) {
$dataLength = count($data);
for ($i=0; $i<$dataLength; $i++) {
call_user_func($callback, $data[$i]);
}
return $data;
}
Isolating the loop into its own function will allow for one line that will execute the wanted callback allowing your main code to be something like (demo)
$data = array(array("foo","bar"),array("hello"),array("world","!"));
function justDump($obj) {
var_dump($obj);
};
$i = 0;
do {
$data = doFor($data, 'justDump');
print "<br>";
$i++;
} while($i<5);
You can also try the way you originally wanted (only slightly edited):
//counter to avoid infinite loop
$counter = 0;
for($i=$i;$i<7;$i++){
echo "<br/>".$i;
if($i == 6){
$i=0;
$counter++;
continue;
}
if($counter == 5){break;}
}
1
2
3
4
5
6
1
2
3
...

PHP Loop do action for each 10, 20, 30 etc [duplicate]

This question already has answers here:
PHP: How do you determine every Nth iteration of a loop?
(8 answers)
Closed 3 years ago.
In php i have loop e.g.
for ($i = 0; $i <= 1000; $i++) {
if ($i = 10 || $i == 20 || $i == 30 || $i == 40 || $i == 50 || $i == 60) {
echo $i;
}
}
imagine i need to echo $i every 10,20,30,40,50,60,..970,980,990 there should be way to not write 100 conditions in if statement. Is there some logical way to see if $i increased by 10 then do something like:
if ($i == $i+10) {
...
}
P.S. if possible i dont want to introduce another variable to count i need to find solution with using only $i
Try:
if ($i % 10 == 0)
That will trigger whenever your index is exactly divisible by 10.
rewrite your for loop to:
for ($i = 0; $i <= 1000; $i+=10) {
And I don't know whether it worked for you with commas like this (as in your initial post):
for ($i = 0, $i <= 1000, $i++) {
Skip extra looping:
for ($i = 10; $i <= 1000; $i=$i+10) {
echo $i;
}
Or if you still want to loop every single digit between:
for ($i = 0; $i <= 1000; $i++) {
if( $i % 10 === 0 ) {
echo $i;
}
}
Test Here
Put this inside your main loop. '%', or 'mod', gives you the remainder of $i / 10. If the remainder is '0', then you want to print.
if(0 === ($i % 10)) {
echo $i;
}

Continue in while with mysql_fetch_assoc

I have a few lines of code, but can't find the right way to use it properly.
$cc = 0;
$tt = 50;
while ($row = mysql_fetch_assoc($result)) {
//building array with values from DB.
if (++$cc < $tt)
continue;
for ($i = 0; $i < $tt; $i++) {
//Work with the array
}
}
Let's say I have 133 results in DB. It'll get first 50 - do something in the for loop, then 50 more, will go thru the for loop again and will stop.
The last 33 results will be untouched.
It'll get them, but cause can't reach 50 will stop and they won't go through the for loop.
My problems is how to "send" them in the loop down there?
Move the for loop in a function and call it after the while loop:
$cc = 0;
$tt = 50;
while ($row = mysql_fetch_assoc($result)) {
//building array with values from DB.
if (++$cc < $tt) continue;
work_with_array($array);
}
if($cc) work_with_array($array);
function work_with_array($array) {
for ($i = 0; $i < count($array); $i++) {
//Work with the array
}
}
Try this:
$i = 0
while ($row = mysql_fetch_assoc($result)):
if($i < 50):
//Code when $i is less than 50
//Insert code here
elseif($i > 50 && $i < 100):
//Code when $i is more than 50 but less than 100
//Insert code here
elseif($i > 100):
//Code when $i is more than 100
//Insert code here
endif;
$i++;
endwhile;
So all results are going through this loop. If $i is less than 50 (or if the result is less than 50) then some code is executed, or if $i is more than 50 but less than 100 then some different code is executed. Finally if $i is more than 100 then some other code is executed.
Do you understand?
You could try:
$i = 0
while ($row = mysql_fetch_assoc($result) && $i < 100):
if($i < 50):
//Code when $i is less than 50
else:
//Code more than or equal to 50
endif;
$i++;
endwhile;
All the continues inside the loop seem unneccesary. If you're simply trying to process the entire result set and do something in chunks, you can do this
$cc = 0;
$tt = 50;
$result_array = array();
// this will chunk your array into blocks
while ($row = mysql_fetch_assoc($result)) {
//building array with values from DB.
$result_array[intval($cc++/$tt)] = $row;
}
// at this point you should have result_array with indexes:0,1,2 and have subarrays with 50, 50, 33 entries each.
foreach ($result_array as $k=>$sub_array) {
//Work with your sub array
foreach ($sub_array as $one_row)
{
// do something with the row
}
}
I do agree with #Col.Shrapnel though. Why are you creating another array inside the while loop just to go through that array one row at a time to do something? It would've made sense if you send out a batch of data at once (like bulk insert into db, sure) but to loop through again seems odd. Why can't you do the same right in the while loop

limit and offset foreach loops

Say i want to loop through XML nodes but i want to ignore the first 10 and then limit the number i grab to 10.
$limit=10; //define results limit
$o=20; //define offset
$i=0; //start line counter
foreach($xml->id AS $key => $value){
$i++;
if($i > $o){
//if line number is less than offset, do nothing.
}else{
if($i == "$limit"){break;} //if line is over limit, break out of loop
//do stuff here
}
}
So in this example, id want to start on result 20, and only show 10 results, then break out of the loop. Its not working though. Any thoughts?
There are multiple bugs in there. It should be
foreach (...
if ($i++ < $o) continue;
if ($i > $o + $limit) break;
// do your stuff here
}
The answer from soulmerge will go through the loop one too many times. It should be:
foreach (...
if ($i++ < $o) continue;
if ($i >= $o + $limit) break;
// do your stuff here
}
You can use next() function for the yours array of elements:
$limit=10; //define results limit
$o=20; //define offset
$i=0; //start line counter
for ($j = 0; $j < $o; $j++) {
next($xml->id);
}
foreach($xml->id AS $key => $value){
$i++;
if($i > $o){
//if line number is less than offset, do nothing.
}else{
if($i == "$limit"){break;} //if line is over limit, break out of loop
//do stuff here
}
}
More information about next() function: http://php.net/manual/en/function.next.php
if($i == $limit+$o){break;}
you should use that cause $limit is reached before $o

Categories