Limiting a for loop - php

So I'm having a small problem with a piece of my code, I have a system that is adding checkpoints to a program and I want it to add a checkpoint every 14 mins, but I also want to limit it to only add x amount of checkpoints based on how many hours a course as. So for an example, the first course has 12 hours so I only want 12 checkpoints created, but it's creating 16 based on the $time_in_secs, so that variable will always be different as its check the time between the start and end date of the program. For the second program, it has 24 hours but its creating 33 checkpoints and so on and so forth. $checkpoint_limit is what I want to limit the for loop by, but I still need it add the 840 as that is the time in seconds and I need a checkpoint created every 14 mins
I have done a few different things but none of them seemed to work. Tried setting a min() also tried doing an if but also does not seem to work.
$checkpoint_limit = (abs($numHours) * 3);
//840 = 14 minute interval * 60
for ($i = 840; $i < $time_in_secs; $i += 840) {
//Code here that adds the checkpoints
}

In for loop check for no of checkpoints created and if they exceed $checkpoint_limit then break the loop.
Try:
$checkpoint_limit = (abs($numHours) * 3);
$no_of_checkpoints = 0;
//840 = 14 minute interval * 60
for ($i = 840; $i < $time_in_secs; $i += 840) {
//Code here that adds the checkpoints
$no_of_checkpoints++;
if($no_of_checkpoints > $checkpoint_limit){
break;
}
}

Use a second condition inside for loop with && operator.For example;
$j=0
for($i=840;$i<$timeInSecs && $j<12;$i +=840)
{
//example code here
$j++
}
I am sorry for the low quality answer i am using SO mobile and could not manage to post the code.So j variable is like a checkpoint time.You have added 14 minute checkpoint and what i get is u want it to loop for a specific count you can do it with that way.And you should increase $j in the end of the for loop.

Related

Why does my PHP code doesn't work anymore for no reason?

I have a for loop in my code. I haven't changed anything on this part of code for about 5-6 days and I never had problems with it.
Since yesterday I tried to reload my code and it allways gives me this error:
Maximum execution time of 30 seconds exceeded - in LogController.php line 270
Well I can't explain why but maybe someone of you could look over it.
This is my code around line 270.
$topten_sites = [];
for ($i = 0; $i <= count($sites_array); $i++) {
if ($i < 10) { // this is 270
$topten_sites[] = $sites_array[$i];
}
}
$topten_sites = collect($topten_sites)->sortByDesc('number')->all();
As I said, it worked perfectly, so why it gives me an error? If I uncomment these lines and every other line that contains the $topten_sites array, the code workes again.
This looks wrong:
for ($i = 0; $i <= $sites_array; $i++) {
if ($i < 10) { // this is 270
$topten_sites[] = $sites_array[$i];
}
}
If $sites_array is an array, it makes no sense to compare it to an integer so you probably have a never-ending loop.
If you just need the first 10 elements in another array, you can replace your loop with:
$topten_sites = array_slice($sites_array, 0, 10);
Why would You iterate entire array if You only want first 10 results?
for ($i = 0; $i < 10; $i++) {
$topten_sites[] = $sites_array[$i];
}
To answer the actual answer; code never stops working "for no reason". Code works or it doesn't, both for a reason. If it stops working something changed compared to your previous tests.
"Sometimes it works, sometimes it doesn't" falls in the same logic. Code will always behave exactly the same every time, just some of the parameters have changed, you have to find which one.
In your case, i'm guessing the entries in your array have increased. PHP and arrays aren't best friends when it comes to speed, arrays are slow. It could very well be that your array was
smaller when you tested it (wasn't probally the fastest to begin with), but now with the current amount it just hit the threshold of 30 seconds.
It could also be that a part of code before this bit of code takes a lot of time (say suddenly 28 seconds instead of 20), and your loop (which never changed) does it's job in the regular 3seconds it always does, now runs into problems
Use it like this:
$topten_sites = [];
for ($i = 0; $i <= 10; $i++) {
$topten_sites[] = $sites_array[$i];
}
$topten_sites = collect($topten_sites)->sortByDesc('number')->all();

Execute every 10 rows

I need help. I need a loop that can execute some codes every 10 rows.
Suppose this is the scenario:
$rows = 15; // The row is for a generated report. I need to put a Thick Border, Horizontally every 10 rows.
This is the loop, and inside it I want another loop or any idea how can I execute some command every 10 rows assuming $row = 15, obviously the command should be executed once since the rows is only 15 and command will execute every 10 rows. Thanks everyone :)
$rows = 15;
for($c=0;$c<$size3;$c++)
{
//Location I want to execute a command every 10 rows.
}
Try for loop for this
for($i = 1;$i <= 40;$i++) {
if($i % 10 == 0) {
// your horizontal code here
} else {
// non horizontal code here
}
}
Edit Remember start the loop from 1 not from 0. See codepad
With 0
With 1
seems there is problem in $rows value, insted of adding condition on $rows %10 ==0 you may try setting one counter $i in loop which will get increment for each row and then you can try adding condition on $i %10 ==0
$startrow = 10 //10 if base 1 or 9 if base 0
$endrow = 15 //you said 15 so lets go with this
for($row = $startrow; $row < $endrow; $row+=10)
{
//do your thing here
}
Since you only want to perform the action once every 10 rows, why not start at row 10, then go by increments of 10 instead of incrementing the row 1 by 1.
This should be more efficient since there will be no wasted loops given your circumstance, it also eliminates the need for checking if the row is divisible by 10.

how to divide sql query result into small parts

i am going to divide a sql query result into two parts. the reason why i want to do this is that i just want my server handle first only 20 items and then after sleep the rest part.
how is it possible in sql to part the query into multiple queries after mysql_query so that i can process the parts separately one after another?
my vision is this:
if(mysql_row_nums($sql)>20){
handle only 20 items
} else {
handle all
}
thanks for reading.
you can do this by setting limit 0,20 in query
Limit is used to limit your MySQL query results to those that fall within a specified range. You can use it to show the first X number of results, or to show a range from X - Y results.
Check out the SQL LIMIT argument:
LIMIT
try
if(mysql_num_rows($sql)>20){
$i = 0;
while($result = mysql_fetch_array($sql)){
$i++;
if($i <= 20){
// do some thing with first 20 result
var_dump($result);
}
if($i == 20){
// if we have arrived to result #20 stop excuting script for minute
sleep(60); // 60 = 1 minute ;
}
if($i > 20){
// continue dealing with result after first 20 result.
}
}
}

PHP to run at intervals within foreach but with added randomness

So i have a foreach and i want to insert a bit of html every say 6 times or maybe 11 times the loop is run.
So my insert on each 13th record
if ($i % 13 == 0) {
}
trouble is i want to add a bit more randomness to it.
Totally forgotten what this is called as well
Something like this will make some code execute $percentage of the time every loop. For example you could set $percent = 20 then your code will execute only 20% of the time each iteration.
$value = rand( 0, 100 ); // Set your ranges (min/max)
$percent = 0; // Set percentage
if ( $percent >= $value )
{
// Will only execute $percentage of the time each loop
}

PHP interval timing

I have a problem, I'm running a script and the PHP line duplicates to whatever number $num_newlines equals. This is what I am currently using:
for ($i=1; $i<=($num_newlines - 1); $i++) {
$tweetcpitems->post('statuses/update', array('status' => wordFilter("The item $array[$i] has been released on Club Penguin.")));
}
What I want to do is have 90 second intervals between however many duplicates are made. So I'm not tweeting like 50 times within 10 seconds. What I want to do is add a 90 second interval between each tweet, please help!
Use the sleep() function:
for ($i = 1; $i <= $num_newlines - 1; $i ++) {
$tweetcpitems->post('statuses/update', array('status' => wordFilter('The item ' . $array[$i] . ' has been released on Club Penguin.')));
sleep(90);
}
This snippet sleeps after every tweet, also after the last one. To prevent sleeping unnecessary after the last tweet, use this:
for ($i = 1; $i <= $num_newlines - 1; $i ++) {
$tweetcpitems->post('statuses/update', array('status' => wordFilter('The item ' . $array[$i] . ' has been released on Club Penguin.')));
if ($i <= $num_newlines - 1) {
sleep(90);
}
}
Two options:
If you can set up CRON jobs - create a queue of messages to post (in a database or file) and let a script run every 90 seconds that takes and removes one message from the queue and sends it.
Use sleep function inbetween sending messages. Note that you may need to increase the time limit (from the comments: under Linux, sleeping time is ignored, but under Windows, it counts as execution time).

Categories