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
}
Related
I am new to php so please mind if it easy question. I have a php script, I want it to be executed only 10 times a day and not more than that. I don't want to use cron for this. Is there any way to do this in php only?
Right now I have set a counter which increases by one every time any one runs the script and loop it to 10 times only. if it exceeds it it shows an error message.
function limit_run_times(){
$counter = 1;
$file = 'counter.txt';
if(file_exists($file)){
$counter += file_get_contents($file);
}
file_put_contents($file,$counter);
if($counter > 11 ){
die("limit is exceeded!");
}
}
I want some efficient way to do this so everyday the script is only executed for 10 times and this is applicable for everyday i.e this counter gets refreshed to 0 everyday or is there any other efficient method.
I would rather recommend that you use a database instead - its cleaner and more simple to maintain.
However, it is achievable with file-handling as well. The file will be of format 2019-05-15 1 (separated by tab, \t). Fetch the contents of the file and split the values by explode(). Then do your comparisons and checks, and return values accordingly.
function limit_run_times() {
// Variable declarations
$fileName = 'my_log.txt';
$dailyLimit = 10;
$content = file_get_contents($fileName);
$parts = explode("\t", $content);
$date = $parts[0];
$counter = $parts[1] + 1;
// Check the counter - if its higher than 10 on this date, return false
if ($counter > $dailyLimit && date("Y-m-d") === $date) {
die("Daily executing limit ($dailyLimit) exceeded! Please try again tomorrow.");
}
// We only get here if the count is $dailyLimit or less
// Check if the date is today, if so increment the counter by 1
// Else set the new date and reset the counter to 1 (as it is executed now)
if (date("Y-m-d") !== $date) {
$counter = 1;
$date = date("Y-m-d");
}
file_put_contents($fileName, $date."\t".$counter);
return true;
}
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.
I'm trying to make a select list of prices in my system. The prices are stored as integers. I'm able to get the lowest price and highest price but I want to display them in a select list. I don't want the select list to increment slowly but by 100 or 10,000 or, 100,000 depending on what my starting number is what where i'm at in my incrementation.
For example, say I have these 2 prices:
500000
12345689
I'm trying to increment them by 100,000 Then when I get to 1,000,000 I want to increment by that. It will look something like this:
500000
600000
700000
800000
900000
1000000
2000000
I'm using a custom function and a bit of formatting to get all my prices and get my start price and end price:
$prices = my_custom_function(); // Pulls All Prices in a random order
if(!empty($prices)){
sort($prices); // Sort Prices Lowest to Highest
$price_low = $prices[0];
$price_high = $prices[count($prices)-1];
$price_start = intval( $price_low[0].str_repeat( '0', strlen( $price_low ) - 1 ) );
$price_end = intval( ( $price_high[0] + 1 ).str_repeat( '0', strlen( $price_high ) -1 ) );
}
Using the same example above, my start price and end price will be:
$price_start = 500000
$price_end = 20000000
Now it's at the loop where I run into trouble incrementing it by the values I want. I'm trying to use a while loop and determine where I am in my incrementer:
<?php $i = $price_start; $x = 0; while($x < 10) : ?>
<option value="<?php echo $i; ?>"><?php echo format_price($i); ?></option>
<?php
if(1000 % $i == 0)
$i+=1000;
else if(10000 % $i == 0)
$i+=10000;
else if(100000 % $i == 0)
$i+=100000;
else if(1000000 % $i == 0)
$i+=1000000;
else
$i+=10000000;
$x++;
endwhile;
?>
I ended up adding in the x variable because I kept running into infinite loop problems but theoretically it should be while($i <= $price_end). Can somebody point me in the right direction on how to get the expected output please? I feel like I'm close but not quite there yet and there's probably a better / faster way to go about it. Any help would be great.
I guess a simplified way of looking at it is:
1 -> +1
10 -> +10
100 -> +100
1000 -> +1000
10000 -> +10000
and so forth.
Get power of 10: log10(1234); // 3.09131
Round down: floor(log10(1234)); // 3
Re-raise as power of 10: pow(10,floor(log10(1234))); // 1000
???
Profit.
If someone needs the full solution here it is:
$price = 100; // Starting Price
$priceEnd = 10000; // Ending Price
while($price <= $priceEnd) {
echo $price . "<br/>";
$increase = pow(10,floor(log10($price)));
$price = $price + $increase;
}
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.
Sorry for the rather unhelpful title, I am trying to make multiple pages for my foreach statement, as it reaches to a database with 100's of rows. Would I limit the query 1,30 for the first page, then 31-60 the second? If so how would I code that?
$totalRows = 100;// Total rows
$perPage = 30;
$pages = ceil($totalRows/$perPage);
for ($i = 0; $i<=$pages; $i++)
{
$sql = sprintf("SELECT * FROM table LIMIT %s, %s", $i*$perPage, $perPage);
// Execute
}
Queries can carry a significant overhead, so don't do multiple queries. Rather, do a single query, then use PHP to break the results up as you wish. You can use a loop counter along with the % operator to check if it's time to do a break.
For instance, if you are looping through results and your loop variable is $i, then you can do:
if ( $i > 0 && $i % 30 == 0 ) {
// Breaking action here ...
}
To detect every 30th iteration of your loop and implement your logic.