Remove last comma from string in while loop - php

My select query is like this, in group_name i am giving comma but I want to remove comma from last. I already tried with trim but it removes all commas, and I want to remove last comma only.
$selctGroup = "SELECT contact_id,group_name FROM contact_group
LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id`
WHERE contact_id = ".$row['contact_id'];
$selctGroupRes = mysql_query($selctGroup);
while($groupRow = mysql_fetch_array($selctGroupRes))
{
echo $groupRow['group_name'].',';
}

Instead of echoing out each line, build up a string to echo at the end. Before that, remove the lingering comma from the end with rtrim($str,",").
$str = "";
while($groupRow = mysql_fetch_array($selctGroupRes)) {
$str .= $groupRow['group_name'].',';
}
echo rtrim($str,",");

$selctGroup = "SELECT contact_id,group_name FROM contact_group
LEFT JOIN `group` ON `group`.`group_id` = `contact_group`.`group_id`
WHERE contact_id = ".$row['contact_id'];
$selctGroupRes = mysql_query($selctGroup);
$str='';
while($groupRow = mysql_fetch_array($selctGroupRes))
{
if($str=='')
$str=$groupRow['group_name'];
else
$str.=','.$groupRow['group_name'];
}
echo $str;

Using rtrim().Like below
rtrim($groupRow['group_name'])

Store your data in array and using implode you can remove last comma
while($groupRow = mysql_fetch_array($selctGroupRes))
{
$result[] = $groupRow['group_name'];
}
echo implode(",", $result);

Related

Remove comma From the last value in a While loop

My main motive is to remove the comma ',' from the last value of the array.
$Followingcount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
if (mysqli_num_rows($Followingcount) > 0) {
while ($ids = mysqli_fetch_assoc($Followingcount)) {
$followedids = $ids['acc_id'].',';
$array = array($followedids);
$arraystr = implode("','",$array);
}}
If I echo $followerdids the result comes like this with commas like:
5, 7, 8,
To remove the comma at the last value I tried to place the values inside an array and then I imploded it.
When I echo $arraystr it still contains the comma at the last value.
All you need is:
$followedIds = [];
$followingCount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
while ($ids = mysqli_fetch_assoc($followingCount )) {
$followedIds[] = $ids['acc_id'];
}
echo implode(',', $followedIds);
...and take care of SQL Injection
The solution to your problem is quite simple. There is a function called rtrim(), which removes all characters on the right side.
$followedids = rtrim($followedids, ',');
There is also a trim() function, which does the same on both sides, and ltrim() which does it for the left side.
You can use rtrim to remove the last comma after the while loop.
$followedids = rtrim($followedids, ',');
You could use the substr-function (more information here)
The last parameter is the length of the substring you want, but you can also use negative values, which means "remove this many characters", in your case: 1.
In your case:
$followedids = substr($followedids, 0,-1);

Remove trailing comma from concatenated query string result

hope you can help, tearing my hair out here!
I have...
$result = mysqli_query($con,'SELECT this FROM that');
while($row = mysqli_fetch_array($result))
{
echo $row['this'] . ',';
}
Which returns...
222,225,243,256,260,269,273,280,295,296,
I need to remove the last comma to give me just...
222,225,243,256,260,269,273,280,295,296
I've tried trim rtrim substr and everything else I could find but none of them work. Think it's to do with the concatenation of the $row['this'] . ',' but I cant figure out how to resolve it!
Any help would be appreciated.
Cheers,
Mark.
Just let MySQL do the work for you:
$result = mysqli_query($con, 'SELECT GROUP_CONCAT(this, ',') as thises FROM that');
This constructs the results as a comma-delimited string. You can refer to it by its name, thises.
Use rtrim to remove last comma.
rtrim($my_string,',');
you can use implode
while($row = mysqli_fetch_array($result))
{
$a[]= $row['this'];
}
$b = implode(',',$a);
print_r($b);
function for implode
function imp($c){
$d= implode(',',$c);
return $d;
}
$b = imp($a);
print_r($b);
You can use substr()
This is your code
$result = mysqli_query($con,'SELECT this FROM that');
while($row = mysqli_fetch_array($result))
{
echo $row['this'] . ',';
}
Code Should like this
$result = mysqli_query($con,'SELECT this FROM that');
$my_string = "";
while($row = mysqli_fetch_array($result))
{
$my_string .= $row['this'] . ',';
}
$my_final_string = substr($my_string, 0, strlen($my_string)-1);
echo $my_final_string;
Explanation
substr(string,start,length)
string = Your generated string
start = From which position you want to start the string.
length = A positive number - The length to be returned from the start parameter. Negative number - The length to be returned from the end of the string

Remove last comma or prevent it from being printed at all MySQL/PHP

I am printing a set of words that is placed in a MySQL database and I am retrieving it with PHP. I want to present it as a comma separated list, but I need it not to print or remove the last comma. How could I do this?
I did try to use rtrim, but I did not probably do it right.
This is my code as it is today:
<?php
$query0 = "SELECT LCASE(ord) FROM `keywords` ORDER BY RAND()";
$result0 = mysql_query($query0);
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keyword = $row0['LCASE(ord)'];
echo "$keyword, ";
?>
I did try to use rtrim, my attempt was something like this (I might be honest enough to say that I am in above my head in this ;) )
$keyword = $row0['LCASE(ord)'];
$keywordc = "$keyword, ";
$keyword- = rtrim($keywordc, ', ');
echo "$keyword-, ";
As you might imagine, this did not print much (but at least it did not leave me with a blank page...)
I would do:
$keywords = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keywords[] = $row0['LCASE(ord)'];
}
echo implode(',', $keywords);
I usually do this by placing the results in an array first
$some_array = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) {
$some_array[] = $row0['LCASE(ord)'];
}
then simply:
echo "My List: " . implode(', ', $some_array);
// Output looks something like:
My List: ord1, ord2, ord3, ord4
substr($string, 0, -1);
That removes the last character.

How to Remove PHP Array Implode Character from Beginning of String

I am working on a project that requires imploding an array with character separation. I have successfully used join and implode interchangeably in other parts of the project, but I can't get it to work in this section.
$dbQuery = "SELECT ftc.*, fc.name
FROM facilities f
LEFT JOIN facility_to_category ftc ON f.fid = ftc.fid
LEFT JOIN facility_categories fc ON ftc.cid = fc.cid
WHERE f.listing_year = '2011'
AND fc.parent_cid = '2'
AND f.fid = ('".$listing_fid."')";
$dbResult = $dbc->query($dbQuery,__FILE__,__LINE__);
$num_results = $dbc->num_rows($dbResult);
echo '<h3>Demographics</h3>
<div>';
while($catdata = $dbc->fetch($dbResult)) {
$demographics = array();
$demographic_names = array('',trim($catdata->name));
$demographics = implode(' '.chr(149).' ',$demographic_names);
print $demographics;
}
The result is this:
Demographics
• Affluent • Children • Hard-to-Reach • Parents
instead of
Demographics
Affluent • Children • Hard-to-Reach • Parents
I've tried using double quotes instead of single quotes around '.chr(149).'. I've tried using commas or bars or just spaces. I've tried different ways of trimming and not trimming $catdata->name.
I also thought about trying string concatenation, but then I'll end up with an extra character at the end instead of the beginning. Implode or join seem the better way to go.
What am I missing?
I am not sure I understand what you are trying to do, but why not use
$demographics_names = array();
while($catdata = $dbc->fetch($dbResult)) {
array_push($demographics_names, trim($catdata->name));
}
$demographics = implode(' '.chr(149).' ',$demographic_names);
print $demographics;
Thank you, everyone, for your help! I ended up reformatting the query and array. Here is the final code:
$dbQuery = "SELECT ftc.*, fc.name
FROM facilities f
LEFT JOIN facility_to_category ftc ON f.fid = ftc.fid
LEFT JOIN facility_categories fc ON ftc.cid = fc.cid
WHERE f.listing_year = '2011'
AND fc.parent_cid = '2'
AND f.fid = ('".$listing_fid."')";
$dbResult = $dbc->query($dbQuery,__FILE__,__LINE__);
$num_results = $dbc->num_rows($dbResult);
echo '<h3>Demographics</h3>
<div>';
while($catdata = $dbc->fetch($dbResult)) {
$demographics = array();
if (is_array($demographics)) {
$demographic_names[] = trim($catdata->name);
}
}
$demographics = join(' '.chr(149).' ',$demographic_names);
print $demographics;
The result is:
Demographics
Affluent • Children • Hard-to-Reach • Parents
Hopefully this will be helpful to someone else!
You're inserting a blank element into the array that you're imploding:
$demographic_names = array('',trim($catdata->name));
^--- here
Seems like you have a blank demographic_name. Use array_filter on the resulting array.
Check the first array is empty.
while($catdata = $dbc->fetch($dbResult)) {
$demographics = array();
$demographic_names = array('',trim($catdata->name));
if(!empty($demographic_names))
{
$demographics = implode(' '.chr(149).' ',$demographic_names);
print $demographics;
}
}

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($query);
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,', ');

Categories