Jump to content

Easy, math related


garry

Recommended Posts

Okay, I have used PHP for a little bit and I'm actually surprised I don't know how to do this..

 

Say I want to run a certain peice of script, I know to use the foreach() function (or while()). I use this when I'm getting results from the database. But what I want to do is run the peice of script a certain amount of times. I think it's got something to do with i++ but i'm not sure how. I just need to know how to make the foreach() loop run 20 times if $times = 20;. Thanks for your help!

Link to comment
https://forums.phpfreaks.com/topic/121825-easy-math-related/
Share on other sites

foreach(); will continue running until there is no more data for it to work with. What you want is a while(); loop. To loop you need to do $i++;

 

like so...

<?php
$times = 20; // run it 20 times
$i = 1; // start at 1
while($i < 20) { // keep looping until $i is equal to 20
echo $i; // display $i
echo "<br />"; // new line
$i++; // $i + 1
}

 

Regards ACE

Link to comment
https://forums.phpfreaks.com/topic/121825-easy-math-related/#findComment-628519
Share on other sites

A foreach() is used on things such as an array which has elements that the foreach() loop will iterrate through.

 

You want a for() loop that willcontinue until a certain condition is met - in this case whern the counter reaces a certain limit,

 

for ($counter=0; $counter<20; $counter++) {

   //Do comething 20 times

}

 

The first expression ($counter=0) is evaluated once (sets the value to 0)

 

The 2nd expression is evaluated on each iterration - if it returns true the loop is run. If it returns false the loop ends.

 

The 3rd expression is evaluated at the end of each iterration (increates the value of $counter by 1)

 

EDIT: I see MasterACE14 has suggested using a while loop. It is valid, but I prefer a for() loop as you can see all the logic in one place - and with a while loop it is easier to forget the step of increasing the counter and you end up with an infinite loop. Your choice.

Link to comment
https://forums.phpfreaks.com/topic/121825-easy-math-related/#findComment-628523
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.