Page is a not externally linkable
- Code, Content, and Presentation
-- PHP Server Side Scripting
---- remove last seperator from array while loop


Frank_Rizzo - 12:57 pm on Apr 6, 2012 (gmt 0)


Two ways to do this.

a) Echo the comma before except on the first instance
b) Build the echo string then strip the last comma

a)

$query = "SELECT * FROM stats";
$result = mysql_query($query) or die(mysql_error());

$row_count = 0;
while($row = mysql_fetch_array($result)){
if($row_count > 0) {
echo ", ";
}
$row_count++;
echo $row['values'];
}

This will not echo the first comma because it is the the first row, then echo the data, then for each subsequent row a comma and data.

b)

$query = "SELECT * FROM stats";
$result = mysql_query($query) or die(mysql_error());
$data = '';

while($row = mysql_fetch_array($result)){
$data .= $row['values'] . ", ";
}
$data = substr(trim($data), 0, -1);
echo $data;

This builds the data string and then before printing it trims (to remove the blank space at the end), and then chops off the last character (the comma)


Thread source:: http://www.webmasterworld.com/php/4437919.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com