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;
You can use the modulus operator:
The expression
$i % 10starts from 0, increases up to 9 (10 – 1) and then “wraps around” indefinitely.$didis 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
$didat 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
or even a standalone
ifstatement.