Reputation: 113
//check which faction members are online
$sql = mysql_query("SELECT * FROM ".TBL_ACTIVE_USERS."
WHERE faction=$userfaction_id ORDER BY timestamp DESC,username");
//no '' around var as it is an integer, so php doesn't expeect it to be string
$numrows = mysql_numrows($sql);//gets number of members online
if($numrows == 1){ echo 'You are the only faction member online'; }
else{
while($online = mysql_fetch_array($sql)){
echo '<a href="#" class="light_grey">'.$online['username'].'</a>';
echo ', ';
}//loops round all online users
//echoing their usernames
}
The above code works fine if only one member is online. The problem is really aesthetic reasons.
If more than one member is online, the query displays:
Administrator, System,
I was wondering how I would make it so on the last result (last member online by the while(){} clause) I could remove the comma? Is there a way of limiting the while statement to $numrows-1 or something along those lines? Then echoing the last user without the comma and space after their name?
Upvotes: 3
Views: 145
Reputation: 56470
implode
is one way to do it, as Pekka showed, one other way is to do it like this:
$first = true;
while($online = mysql_fetch_array($sql)){
if (!$first) {
echo ', ';
$first = false;
}
echo '<a href="#" class="light_grey">',$online['username'],'</a>';
}
Should be a bit more efficient than the implode
way if there's a lot of online members, due to not having to construct a temporary array.
Upvotes: 1
Reputation: 14375
<?php
$i = 0;
while{
if($i > $numrows)
{
echo ', ';
}
$i++;
}
Upvotes: 0
Reputation: 449823
One elegant way is to use an array and implode()
.
$elements = array();
while($online = mysql_fetch_array($sql)){
array_push ($elements, '<a href="#" class="light_grey">'.
$online['username'].'</a>');
}
echo implode(", ", $elements);
Upvotes: 5