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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With