get rid of last comma in a loop in php [duplicate] - php

This question already has answers here:
PHP Mysql WHILE loop remove the last separator
(4 answers)
Closed 6 years ago.
I'm trying to send mulitple sms and the correct format for the api to send the text messages should be (00,001,002) but with my current sql it produces this results (00,001,002,)
How can i correct my script to get this results (00,001,002)
$query_rs_p = "SELECT * FROM contacts ORDER BY id DESC";
$rs_p = mysql_query($query_rs_p, $insurance) or die(mysql_error());
$row_rs_p = mysql_fetch_assoc($rs_p);
$totalRows_rs_p = mysql_num_rows($rs_p);
$ph=',';
do {
echo $row_rs_p['phone_number'].$ph;
} while ($row_rs_p = mysql_fetch_assoc($rs_p));

Instead of echoing it out in your loop, put it all in a string. Then trim off the last comma before you output it:
$query_rs_p = "SELECT * FROM contacts ORDER BY id DESC";
$rs_p = mysql_query($query_rs_p, $insurance) or die(mysql_error());
$row_rs_p = mysql_fetch_assoc($rs_p);
$totalRows_rs_p = mysql_num_rows($rs_p);
$ph=',';
$string = '';
do {
$string .= $row_rs_p['phone_number'].$ph;
} while ($row_rs_p = mysql_fetch_assoc($rs_p));
$string = rtrim($string, ',');
echo $string;
Or, better yet, just build this string in your query. Much simpler and cleaner:
$query_rs_p = "SELECT group_concat(phone_number) as phine_numbers FROM contacts ORDER BY id DESC";
$rs_p = mysql_query($query_rs_p, $insurance) or die(mysql_error());
$row_rs_p = mysql_fetch_assoc($rs_p);
echo $row['phone_numbers'];

Use rtrim function
$rowsphone = $row_rs_p['phone_number'].$ph;
rtrim($rowsphone,',');

Probably the most direct would be to just do something like this:
$output = '';
do {
if ($output != '')
$output .= ',';
$output .= $row_rs_p['phone_number'];
while ($row_rs_p = mysql_fetch_assoc($rs_p);
echo $output;

Related

last element in while loop php [duplicate]

This question already has answers here:
Removing last comma from a foreach loop
(9 answers)
Closed 5 years ago.
$result = $conn->query("SELECT * FROM mails");
while($row = $result->fetch_assoc()){
$mymail= $row['mail']. ",";
echo $mymail;
}
I have after every row comma (,) but I don't want (,) after last row. How could I do this?
Take a look at the join function:
$mails = array();
$result = $conn->query("SELECT * FROM mails");
while($row = $result->fetch_assoc())
{
$mails[] = $row['mail']; // Store E-Mail adresses in an array
}
$commaSeparatedMails = join(',', $mails); // Connect all array parts using a comma
echo $commaSeparatedMails;
rtrim(yourstring,","), this function will remove right comma.

Remove last comma from string in while loop

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);

How to add comma on preg_match like this

This is my sample preg_match and working, but how to add Comma "," on code already like bellow
$content = explode(" ",$title);
$result = "";
foreach($content as $value){
if(!preg_match("/\.|'/",$value)){
$find = mysqli_query($db, "select * from table where column1='$value'");
$j = mysqli_num_rows($find);
if($j>0){
$ka = mysqli_fetch_array($find);
$result = $result.$ka['column2'];
}else{
$find2 = mysqli_query($db, "select * from table where column2='$value'");
$j2 = mysqli_num_rows($find2);
if($j2>0){
$ka2 = mysqli_fetch_array($find2);
$result = $result.$ka2['column1']);
}else{
$result = $result.$value;
}
}
}else{
}
i just try like this but not work
if(!preg_match("/\.\,|'/",$value)){
blablabla
}else{
blablabla
}
because I am still learning php so confused what to do, thank you if anyone would like to help
I assume you want to match a list of characters, use the character class [] instead like:
if(!preg_match("/[.,']/",$value)){
blablabla
}else{
blablabla
}
Learning regex is invaluable, read up on it and it'll pay for itself in a month!

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.

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