Page 1 of 1
IF Statement for WHILE loop
Posted: Sun Jan 25, 2009 5:30 pm
by Deuce
Hi, I have a simple while statement that grabs a list of categories from the database.
I wil be using AJAX to make the links functional, but basically I need to figure out an easy way for the last time the while loop runs it will not print out the pipe |
Is there an easy if statement I can put within the while loop?
if(last loop) { do this } else { run loop again }??
Code: Select all
$catList = mysql_query("SELECT * FROM adminCategory ORDER BY CategoryName");
while ($catlistRow = mysql_fetch_array($catList)) {
print '<a href="" class="sortCat">'.$catlistRow{'CategoryName'}.'</a> | ';
}
Re: IF Statement for WHILE loop
Posted: Sun Jan 25, 2009 5:48 pm
by Mark Baker
Reverse your thinking. Print out the pipe before each entry, and don't print it the first time.
Code: Select all
$catList = mysql_query("SELECT * FROM adminCategory ORDER BY CategoryName");
$i = 0;
while ($catlistRow = mysql_fetch_array($catList)) {
if ($i > 0) {
print ' | ';
$i++;
}
print '<a href="" class="sortCat">'.$catlistRow{'CategoryName'}.'</a>';
}
Re: IF Statement for WHILE loop
Posted: Sun Jan 25, 2009 6:13 pm
by John Cartwright
Mark Baker wrote:Reverse your thinking. Print out the pipe before each entry, and don't print it the first time.
Code: Select all
$catList = mysql_query("SELECT * FROM adminCategory ORDER BY CategoryName");
$i = 0;
while ($catlistRow = mysql_fetch_array($catList)) {
if ($i > 0) {
print ' | ';
$i++;
}
print '<a href="" class="sortCat">'.$catlistRow{'CategoryName'}.'</a>';
}
I always try to avoid logic within a loop (when possible).
Code: Select all
$links = array();
while ($catlistRow = mysql_fetch_array($catList)) {
$links[] = '<a href="" class="sortCat">'. $catlistRow['CategoryName'] .'</a>';
}
echo implode(' | ', $links);
P.s. You are using curly brackets for array indices when they should be square brackets.
Re: IF Statement for WHILE loop
Posted: Sun Jan 25, 2009 6:53 pm
by Deuce
both options look good.
Jcart, for learning purposes, why do you avoid logic in your loops?
Thanks for the help!
Re: IF Statement for WHILE loop
Posted: Sun Jan 25, 2009 7:56 pm
by John Cartwright
To optimize the code. If we can avoid running code over and over within a loop (more computer cycles), then you should do so. In a language like PHP this usually isn't a problem, but it is considered good practice.
I also find it much easier to debug an array than a bunch of strings, especially for a simple collection loop like yours. I.e. ability to manipulate the array and output much cleaner, var_export() for instance.