PHP - Delete last 2 characters in a loop
I have the following which produces results for me.
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($q开发者_C百科uery);
echo $author['fullname'] .', ';
}
It prints it out perfect, except on the last run it still adds the comma and space, is there a way i can strip this from the last result, so its:
name, name, name, name
Instead of the following
name, name, name, name,
Cheers
A better way of doing this would be to separate out the handling of database results from the view/output logic, and then you can sidestep the issue all together, using implode
to allow PHP to join each of your authors together into a single string, split by your delimiter of a comma and a space:
// your loop {
$authors[] = $author['fullname'];
}
// your output
echo implode(', ', $authors);
Just concate the data into a string and then remove the last 2 chars using
$author['fullname'] = substr($author['fullname'], 0, -2);
Refer the manual for substr
http://php.net/manual/en/function.substr.php
Instead of echoing each author out you could put them in a string and then simply use trim() to take off the trailing comma and finally echo the whole string.
this will probably work
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
//echo $author['fullname'] .', ';
}
$name_count = count($author[]);
for($x=0;$x<$name_count ;$x++){
if($x == $name_count -1){
echo $author['fullname'];
}else{
echo $author['fullname'].", ";
}
}
the idea is to detect the last array index, so that we can apply all the commas after each name except to the last one.
don't ever echo inside foreach
$var = '';
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
$var .= $author['fullname'] .', ';
}
echo trim($var,', ');
精彩评论