Loop x number of times
Moderator: General Moderators
Loop x number of times
Okay, so how do I loop something (eg get top10 id's from db ordered by ascending) for lets say 10 times?
Re: Loop x number of times
Two separate questions, two separate answers.
Use the appropriate SQL query.tonchily wrote:get top10 id's from db ordered by ascending
Use a for loop.tonchily wrote:Okay, so how do I loop something...for lets say 10 times?
Re: Loop x number of times
Is there any other way? I can't get to figure out how for loop works.tasairis wrote: Use a for loop.
- greyhoundcode
- Forum Regular
- Posts: 613
- Joined: Mon Feb 11, 2008 4:22 am
Re: Loop x number of times
There are various forms of looping that you might use in addition to for loops, such as a while loop or do while, they are worth reading up on.
Regarding a for loop:
The first thing to notice is $i = 0, this sets the variable $i to zero. Then we have the condition $i <= 10 which means the stuff inside the for loop will keep running so long as $i does not exceed 10. Finally $i++ increments the value of $i by one, which will happen at the end of each cycle through the loop.
Don't know if that helps you at all, but you never know...
Regarding a for loop:
Code: Select all
for ($i = 0; $i <= 10; $i++)
{
// Do stuff in here
echo "$i <br/>";
}Don't know if that helps you at all, but you never know...
Re: Loop x number of times
Yeah, thanks. Think it just helped.greyhoundcode wrote:There are various forms of looping that you might use in addition to for loops, such as a while loop or do while, they are worth reading up on.
Regarding a for loop:The first thing to notice is $i = 0, this sets the variable $i to zero. Then we have the condition $i <= 10 which means the stuff inside the for loop will keep running so long as $i does not exceed 10. Finally $i++ increments the value of $i by one, which will happen at the end of each cycle through the loop.Code: Select all
for ($i = 0; $i <= 10; $i++) { // Do stuff in here echo "$i <br/>"; }
Don't know if that helps you at all, but you never know...
The first I do is run a query where it sorts users by their points descending. After that, my $i variable was actually my id variable, so it "fetched" (dunno if it's the right word) the top10 ones. Thanks for help.
Re: Loop x number of times
You shouldn't use a loop for this. (Which is why tasairis said your question was actually two questions.)tonchily wrote:how do I [...] get top10 id's from db
Use a query with a LIMIT clause.
Code: Select all
SELECT id FROM table_name ORDER BY id LIMIT 10; # The first 10 results (0-9)
SELECT id FROM table_name ORDER BY id LIMIT 0, 10; # Also the first 10 results (0-9)
SELECT id FROM table_name ORDER BY id LIMIT 10, 10; # The next 10 results (10-19)
# This is a comment