Removing last comma from a foreach loop
Put your values in an array and then implode
that array with a comma (+ a space to be cleaner):
$myArray = array();
foreach ($this->sinonimo as $s){
$myArray[] = '<span>'.ucfirst($s->sinonimo).'</span>';
}
echo implode( ', ', $myArray );
This will put commas inbetween each value, but not at the end. Also in this case the comma will be outside the span, like:
<span>Text1<span>, <span>Text2<span>, <span>Text3<span>
How to remove the last comma from foreach loop?
By placing the HTML in a simple string variable and then using rtrim()
on the resulting string before outputting it this should remove the final ,
from the string
<?php
$out = '';
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
// move inside loop and amend to place in a simple string var
$out .= '<a href="' . base_url() . 'tags/' . $tag_name . '">' . $tag_name . '</a>,';
?>
echo rtrim($out, ',');
Removing Last Comma in a For & Foreach Loop
Do not display the text immediately. "Cache it" and then display it, but remove the last character either by substr or rtrim
for ($i = 0; $i < $compatibilitycount; $i++) {
$result = '';
foreach ($xml->Item->ItemCompatibilityList->Compatibility[$i] as $compatibility ) {
if ($compatibility->Value != '') {
$result .= $compatibility->Value . ',';
}
}
echo substr($result, 0, -1) . '<br />';
// or echo rtrim($result, ',') . '<br />';
}
How to remove the last comma in for loop
<?php
for( $x=1 ; $x<=10 ; $x++){
echo "$x";
if($x!=10)
echo ",";
}
?>
Check for the last iteration and avoid ','
How to remove the last comma from the last item generated from a foreach loop, inside a function
Simply trim() it with your own character list
foreach ($jsonbreadcrumbs as $crumb) {
$link = ucwords(str_replace(array(".php","-","_"), array(""," "," "), $crumb));
$root_domain .= $crumb . '/';
$jsonbreadcrumb .= '{"@type": "ListItem",';
$jsonbreadcrumb .= '"position":' . $itemNumber++ . ',';
$jsonbreadcrumb .= "\"name\": \"{$link}\",";
$jsonbreadcrumb .= "\"item\": \"{$root_domain}\"},";//<---this last comma,when it belongs to the last item, needs to be removed.
}
$jsonbreadcrumb=trim($jsonbreadcrumb,","); // this removes that trailing comma...
$jsonbreadcrumb .= ']}</script>';
remove last comma from string in while loop in php?
Take the post titles in an array and Use Implode instead ..
<?php
$cat = get_terms('car_category'); // you can put your custom taxonomy name as place of category.
foreach ($cat as $catVal) {
echo '<b>'.$catVal->name.'</b>';
$postArg = array('post_type'=>'cars','posts_per_page'=>5,'order'=>'desc',
'tax_query' => array(
array(
'taxonomy' => 'car_category',
'field' => 'term_id',
'terms' => $catVal->term_id
)
));
$getPost = new wp_query($postArg);
global $post;
if($getPost->have_posts()){
$str = array();
while ( $getPost->have_posts()):$getPost->the_post();
$str[] = $post->post_title;
endwhile;
}
echo '<div class="yearDiv">';
echo '<span>'.implode(', ', $str).'</span>';
echo '</div>'
}
?>
Remove comma from last result in nested forEach loop
I'd use map/join:
const email = "john@gmail.com";
const body = {
"fruit": ["apple"],
"vegetables": ["carrot", "beans"],
"dairy": ["milk", "cheese"]
};
const values = Object.keys(body)
.map(key =>
body[key]
.map(item => `('${item}', '${key}', '${email}')`)
.join(', ')
)
.join(', ');
console.log(values);
Remove foreach last comma PHP
One way to solve this is to not echo out the commas in the foreach
loop. Put the data you want to echo into an array, then use implode
.
$output = array();
foreach($result as $r) {
$output[] = $r['lenght'];
}
echo implode(',', $output);
Related Topics
Seamless Way to Check If User Likes Page
Check If String Contains a Value in Array
How to Write Cdata Using Simplexmlelement
PHP Random Shuffle Array Maintaining Key => Value
What Can Use for Datetime::Diff() for PHP 5.2
How to Sort an Array of Utf-8 Strings in PHP
What Is a Unix Timestamp and Why Use It
How to Read Only 5 Last Line of the Text File in PHP
Generating Xml Document in PHP (Escape Characters)
Regex Pattern to Get the Youtube Video Id from Any Youtube Url
How to Handle Error for Duplicate Entries
Leverage Browser Caching for 3Rd Party Js
How Do Detect That Transaction Has Already Been Started
Pdo MySQL: Insert Multiple Rows in One Query
Create Programmatically a Variable Product and Two New Attributes in Woocommerce