简体   繁体   中英

Increment int var every 10 iterations of loop

I'm building a long query of dummy data. I have a for loop running a few thousand times, in each loop, it adds a new row to a query, with the increment variable used for dummy file names, 1.png, 2.png etc. I also need to increment a separate foreign key id, but it needs to only be every 10 iterations of the loop. can anyone help? Thanks.

$var = '';
for($i=0;$i<100;$i++){
    $path = '/test' . $i . '.pdf';
    $mess = 'Test message '. substr(md5($i), 0, 10);
    $did = 0;//How to increment this var by 1 every 10 iterations?
    $var .= "INSERT INTO `message` (`design_id`, `path`, `message`) VALUES ('$did', '$path', '$mess');"."<br />";
}
echo $var;

$i+=10

Example:

for ($i=0; $i<100; $i+=10) {
}

You can use the modulus operator :

$did = 0;
for($i=0;$i<100;$i++){
    $did += $i % 10 == 9;
}

The expression $i % 10 starts from 0, increases up to 9 (10 - 1) and then "wraps around" indefinitely. $did is increased every time it evaluates to 9, which is every 10 iterations.

It's interesting to note that you can use any value in the range [0, 9] for the comparison and it will still increase $did at the same rate; the difference is when the first increase will happen. By choosing 9 increases happen on the 10th, 20th, etc iteration. If you chose 0 instead, increases would happen on the 1st, 11th, 21st, etc.

Finally, if this technique is new it might feel more comfortable to use extra parens, for example

$did += ($i % 10 == 9);

or even a standalone if statement.

Divide and floor.

$did = floor(i / 10);

$var = '';
$did = 0;
for($i=1;$i<=100;$i++){
    $path = '/test' . $i . '.pdf';
    $mess = 'Test message '. substr(md5($i), 0, 10);
    if((i % 10) == 0){
          $did++;
     }
    $var .= "INSERT INTO `message` (`design_id`, `path`, `message`) VALUES ('$did', '$path', '$mess');"."<br />";
}
echo $var;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM