Removing last comma in the foreach query in php mysql - php

Im using a foreach loop to echo out some values from my database and seperating each of them by commas but last comma how we can remove
echo $string='"paymentmethods":';
echo $string='"Bank":[';
$sql2 = "SELECT * FROM paymentmethods where cid=587 ";
$query = $this->db->query($sql2);
foreach ($query->result() as $row){
echo '{';
echo $string = 'accname:'.$row->acc.',' ;
echo $string = 'country:'.$row->IBAN.',' ;
echo $string = 'Iban:'.$row->Bankname.',' ;
echo $string = 'Bankname:'.$row->Bankname.',' ;
echo $string = '},';
}
echo $string = '],';
"paymentmethods":"Bank":[{accname:0034430430012,country:AE690240002520511717801,Iban:ARABIC BANK NAME,Bankname:ARABIC BANK NAME,},{accname:0506796049,country:DE690240002520511717801,Iban:ARABIC BANK NAME,Bankname:ARABIC BANK NAME,},]
Here see the comma is repeating after the name ends. and also after the end of brackets

The comma is there because you have written it in your code. Change the lines to this :
// same as above
echo $string = 'Bankname:'.$row->Bankname. ;
echo $string = '}';
}
echo $string = ']';

a common way to do this is to do this way :
$sep = '';
$result = '';
foreach($myarray as $value) {
$result .= $sep.$value;
$sep = ',';
}
this way, you don't have a beginning or ending comma.
But as comments say, you are doing a "json_encode" by yourself... you should use json_encode / decode instead.

Related

How to reformat a string of words with commas/ampersands in PHP

I am trying to write some PHP code that will separate words when the are two with "&" and a comma when they are three and the last two with "&"
Something like this
$string = "stack over flow";
Print on screen like this "stack, over & flow";
Hope you noticed the comma and the ampersand.
Then when they are two words
$string = "stack overflow";
print like this echo "stack & overflow";
Here is my code I have been trying, but I am not getting it right:
$string = '1,2';
$list = explode(',',$string);
foreach($list as $row) {
if($list = 2) {
echo ''.$row.' &';
}
}
This should take into account the possibilities of one or more words. If there is more than one word, just remove the last word (using array_pop()) and implode() with , the remaining words.
If there is only 1 word, the result is the same as the original string...
$string = "stack over";
$list = explode(" ", $string);
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = implode(", ", $list) . " & {$last}";
}
else {
$result = $string;
}
To add anchor tags to each word...
$list = explode(" ", $string);
$aTag = '<a href="#">';
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = $aTag.
implode("</a>, {$aTag}", $list) . "</a> & {$aTag}{$last}</a>";
}
else {
$result = $aTag.$string."</a>";
}
echo $result;
thanks Nigel Ren.. you code was really helpfully
but their a correction i made.Here
$string = "stack over flow";
$list = explode(" ", $string);
$aTag = '<a href="#">';
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = $aTag.
implode('</a>, '.$aTag.'', $list) . "</a> & {$aTag}{$last}</a>";
}
else {
$result = $aTag.$string."</a>";
}
echo $result;
thanks

PHP remove the last character from my loop

I'm writing a string from my form and I'd like to remove the last comma from the end. I understand that I can use the rtrim(), but I don't understand how I can return a variable from my loop. I'm sure this is an easy answer, just super confused. Thanks!
if (isset($_POST['submit'])) {
foreach ( $_POST['data'] as $data )
{
echo $data['Monday'];
echo $data['Tuesday'];
echo $data['Wednesday'];
echo $data['Thursday'];
echo $data['Friday'];
echo $data['Saturday'];
echo $data['Sunday'];
echo ", ";
}
} // end if
You can check if you are on the last element and skip printing the comma if so:
end($_POST['data'); // fast forward to the end of the array
$lastKey = key($_POST['data'); // and remember what the last key is
foreach ( $_POST['data'] as $key => $data )
{
echo $data['Monday'];
echo $data['Tuesday'];
echo $data['Wednesday'];
echo $data['Thursday'];
echo $data['Friday'];
echo $data['Saturday'];
echo $data['Sunday'];
if ($key !== $lastKey) echo ", ";
}
This approach feels cleaner to me: prevention is better than treatment.
you need to have a variable
$str = null;
if (isset($_POST['submit'])) {
foreach ( $_POST['data'] as $data )
{
$str .= $data['Monday'] .
$data['Tuesday'] .
$data['Wednesday'] .
$data['Thursday'] .
$data['Friday'] .
$data['Saturday'] .
$data['Sunday'] .
", ";
}
$str = substr($str,0,-2);
}
Then you have the data in $str which you can then echo or do stuff with
You could get the last index of the $_POST['data'] and simply not echoing a , when that's reached:
end($_POST['data']);
$last_key = key($_POST['data']);
foreach ($_POST['data'] as $key => $data) {
// echoes here
if ($key != $last_key) {
echo ',';
}
}
Instead of echo'ing the data immediately, store it in a buffer...
if (isset($_POST['submit'])) {
$buffer = "";
foreach ( $_POST['data'] as $data )
{
$buffer .= $data['Monday'];
$buffer .= $data['Tuesday'];
$buffer .= $data['Wednesday'];
$buffer .= $data['Thursday'];
$buffer .= $data['Friday'];
$buffer .= $data['Saturday'];
$buffer .= $data['Sunday'];
$buffer .= ", ";
}
$buffer = rtrim($buffer, ", ");
echo $buffer;
} // end if
Or, even shorter:
if (isset($_POST['submit'])) {
implode(", ", $data);
} // end if
Assuming $data only has those Monday-Sunday keys..

PHP - remove comma from the last loop

I have a PHP while LOOP, and I want to remove last comma , from echo '],'; if it is last loop
while($ltr = mysql_fetch_array($lt)){
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo '],';
}
Create an array with the elements as you go along so that they look like array = ([ELEMENT INFO], [ELEMENT INFO], [ELEMENT INFO]) and then implode the array with a comma.
$str = '';
while($ltr = mysql_fetch_array($lt)){
$str .= '[';
$str .= $ltr['days']. ' ,'. $ltr['name'];
$str .= '],';
}
echo rtrim($str, ",");
this will remove the last , from string
I think the systemic solution is following:
$separator = '';
while($ltr = mysql_fetch_array($lt)){
echo $separator;
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if (!$separator) $separator = ', ';
}
No call for count(), no additional iteration of implode(), no additional string operations, ready for any (unpredictable) number of results.
$result = mysql_fetch_array($lt);
for ($i=0;$i<=(count($result)-1);$i++) {
$ltr = $result[$i];
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if(!count($result)-1 == $i){
echo ',';
}
}
Check how many entries you have, make a "Counter" and a condition to only put the comma when its not the last loop.
$arr = array();
while($ltr = mysql_fetch_array($lt)){
$arr[] = '[' . $ltr['days'] . ' ,' . $ltr['name'] . ']';
}
echo implode(',', $arr);
$res_array = array();
while($ltr = mysql_fetch_array($lt)){
$res_array[] = '['.$ltr['days']. ' ,'. $ltr['name'].']';
}
$str = implode(",",$res_array);
echo $str;
Save the response as a var instead of echoing it and then remove the final character at the end using substr.
$response = "";
while($ltr = mysql_fetch_array($lt)){
$response .= '[';
$response .= $ltr['days']. ' ,'. $ltr['name'];
$response .= '],';
}
echo substr($response, 0, -1);
//this one works
$result = mysql_fetch_array($lt);
for ($i=0;$i<=(count($result)-1);$i++) {
$ltr = $result[$i];
echo '[';
echo $ltr['days']. ' ,'. $ltr['name'];
echo ']';
if(count($result)-1 != $i){
echo ',';
}
}

Write a dot instead of a comma when it's last element in PHP

I have a while loop use to write a list. i'd like every element separated with a comma, but write a dot after the last one, not a coma.
Here is my code
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
echo '<strong>'.$row['name'].'</strong>, ';
}
But I don't know how to do that. I tried using count() or end(), but none of these works. A little help would be great !
$html = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$html[] = '<strong>' . htmlspecialchars($row['name']) . '</strong>';
// --------------------^^^^^^^^^^^^^^^^! (1)
}
$html = implode(', ', $html) . '.';
(1) - Never output data to HTML without escaping it properly.
I like the use the implode function for this :)
$list = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$list[] = '<strong>'.$row['name'].'</strong>';
}
$string = implode(", " , $list);
echo $string . ".";
HTH
Try this:
$exec = mysql_query($req);
$output = array();
while ($row = mysql_fetch_assoc($exec)){
$output[] = '<strong>'.$row['name'].'</strong>';
}
echo implode(',', $output), '.';
Build the string but don't output. Then, trim off the command and add a fullstop:
$exec = mysql_query($req);
$output = "";
while ($row = mysql_fetch_assoc($exec))
{
$output .= '<strong>'.htmlentities($row['name']).'</strong>, ';
}
if($output) echo rtrim($output, ', ').".";

Create a comma-separated string from a single column of an array of objects

I'm using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.
My loop is just simple, as below
foreach($results as $result){
echo $result->name.',';
}
Which echos out
result,result,result,result,
I just need to kill that pesky last comma.
Better:
$resultstr = array();
foreach ($results as $result) {
$resultstr[] = $result->name;
}
echo implode(",",$resultstr);
1. Concat to string but add | before
$s = '';
foreach ($results as $result) {
if ($s) $s .= '|';
$s .= $result->name;
}
echo $s;
2. Echo | only if not last item
$s = '';
$n = count($results);
foreach ($results as $i => $result) {
$s .= $result->name;
if (($i+1) != $n) $s .= '|';
}
echo $s;
3. Load to array and then implode
$s = array();
foreach ($results as $result) {
$s[] = $result->name;
}
echo implode('|', $s);
4. Concat to string then cut last | (or rtrim it)
$s = '';
foreach ($results as $result) {
$s .= $result->name . '|';
}
echo substr($s, 0, -1); # or # echo rtrim($s, '|');
5. Concat string using array_map()
echo implode('|', array_map(function($result) { return $result->name; }, $results));
$result_names = '';
foreach($results as $result){
$result_names .= $result->name.',';
}
echo rtrim($result_names, ',');
I've been having the same issue with this similar problem recently. I fixed it by using an increment variable $i, initializing it to 0, then having it increment inside the foreach loop. Within that loop place an if, else, with the echo statement including a comma if the $i counter is less than the sizeof() operator of your array/variable.
I don't know if this would fix your issue per se, but it helped me with mine. I realize this question is years-old, but hopefully this will help someone else. I'm fairly new to PHP so I didn't quite understand a lot of the Answers that were given before me, though they were quite insightful, particularly the implode one.
$i=0;
foreach ($results as $result) {
$i++;
if(sizeof($results) > $i) {
echo $result . ", ";
} else {
echo $result;
}
}
In modern PHP, array_column() will allow you to isolate a column of data within an array of objects.
Code: (Demo)
$results = [
(object)['name' => 'A'],
(object)['name' => 'B'],
(object)['name' => 'C']
];
echo implode(',', array_column($results, 'name'));
Output:
A,B,C
That said, since you are iterating a result set, then you may be better served by calling a CONCAT() function in your sql, so that the values are already joined in the single value result set.
If you are processing a collection in Laravel, you can pluck() and implode():
$collection->pluck('name')->implode(',')
$arraySize = count($results);
for($i=0; $i<$arraySize; $i++)
{
$comma = ($i<$arraySize) ? ", " : "";
echo $results[$i]->name.$comma;
}
Not as pretty, but also works:
$first=true;
foreach($results as $result){
if(!$first) { echo ', '; }
$first=false;
echo $result->name;
}
Another smart way is:
foreach($results as $result){
echo ($passed ? ',' : '') . $result->name;
$passed = true;
}
In this case at first loop $passed is NULL and , doesn't print.
I know this is an old thread, but this came up recently and I thought I'd share my alternate, cleaner way of dealing with it, using next().
$array = array("A thing", "A whatsit", "eighty flange oscillators");
foreach( $array as $value ){
echo $value;
$nxt = next($array);
if($nxt) echo ", "; // commas between each item in the list
else echo ". And that's it."; // no comma after the last item.
}
// outputs:
// A thing, A whatsit, eighty flange oscillators. And that's it.
play with it here
I have to do this alot because I'm always trying to feed numbers in to jplot, I find its easier to put the comma in the front of the loop like so:
foreach($arrayitem as $k){ $string = $string.",".$k;
}
and then chop off the first character (the comma) using substr, it helps if you know a guestimate of long your string will be, I'm not sure what the limit on substr max character is.
echo substr($a,1,10000000);
hope this helps.
$a[0] = 'John Doe';
$a[1] = 'Jason statham';
$a[2] = 'Thomas Anderson';
$size = count($a);
foreach($a as $key=>$name){
$result .= $name;
if($size > $key+1) $result .=', ';
}
echo $result;
<?php
$return = array(any array)
$len = count($return);
$str = '';
$i = 1;
foreach($return as $key=>$value)
{
$str .= '<a href='.$value['cat_url'].'>'.$value['cat_title'].'</a>';
if($len > $i)
{
$str .= ',';
$i = $i+1;
}
}
echo $str;
?>
<?php
$i = 1;
$count = count( $results );
foreach( $results as $result ) {
echo $result->name;
if ( $i < $count ) echo ", ";
++$i;
}
?>
This is what I normally do, add a comma before the item rather than after, while ignoring the first loop.
$i = 0;
$string = '';
foreach($array as $item){
$string .= ($i++ ? ',' : '').$item;
}
First get all the output by using output buffering. Then, trim the comma and display it. So, do it like this:
ob_start();
foreach($results as $result)
{
echo $result->name.',';
}
$output = ob_get_clean();
echo rtrim($output, ',');
The output buffering method helps if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals of the loop.

Categories