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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.