Welcome to WebmasterWorld Guest from 54.196.176.3

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

remove last seperator from array while loop

     

Chunter

11:31 am on Apr 6, 2012 (gmt 0)



Hi,

I'm having an issue, I'm trying to display mysql data with a php query in some javascript to display a chart.

this is my php:


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

while($row = mysql_fetch_array($result)){
echo $row['values'] . ", ";
}

The return generates the following:

10000, 20000, 15000, 5000, 20000, 23000, 10000,

That result has to remove the last ", " so the new result is:

10000, 20000, 15000, 5000, 20000, 23000, 10000

Can someone plz help?
Thanks

Frank_Rizzo

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

WebmasterWorld Senior Member 10+ Year Member



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)

Chunter

1:51 pm on Apr 6, 2012 (gmt 0)



Thanks for the quick reply, however I think something is going wrong. I took over both methods and both generate this error:

Notice: Undefined index: values in H:\xampp\htdocs\stats\highcharts.php on line 121

What am I doing wrong plz?
thx

Frank_Rizzo

3:37 pm on Apr 6, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What is in line 121

?

rocknbil

4:34 pm on Apr 6, 2012 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



I like to use option b with preg_replace. :-) It's less lines of code (no counter and if's) and executes a mod on the output once.

$data = preg_replace('/,\s+$/','',$data);

Chunter

5:31 pm on Apr 6, 2012 (gmt 0)



Thanks for all the help it works perfect now
 

Featured Threads

Hot Threads This Week

Hot Threads This Month