I am trying to fetch data from a table, and when I need to print the result then I am using comma separator to split the result. But I don't want to show the last comma.
Please see the code below:
<?php if($result_sender2):
foreach($result_sender2 as $row_sender2):
echo $row_sender2->fname.',';
endforeach;
endif;
?>
and the result is
Kunal,James,
here in the above example, I am using a comma separator. It works fine for me, but I don't want to show the last comma after "James".
You can use trim function
<?php
$list = "";
if($result_sender2):
foreach($result_sender2 as $row_sender2):
$list = $list . $row_sender2->fname.',';
endforeach;
endif;
$list = trim($list, ",");
echo $list
?>
Check if it's the last object in the array:
<?php
if($result_sender2):
$arrayLength = count($result_sender2);
foreach($result_sender2 as $row_sender2):
if(array_search($row_sender2,$result_sender2)+1 !== $arrayLength):
echo $row_sender2->fname.',';
endif;
endforeach;
endif;
?>
You can get all values you need in one array and perform implode() funciton on it - http://php.net/manual/en/function.implode.php
Try This one
if($result_sender2):
$cnt = sizeof($result_sender2);
$i=0;
$str = "";
foreach($result_sender2 as $row_sender2):
$str .= $row_sender2->fname;
if($i<$cnt)
{
$str .= ",";
}
$i++;
endforeach; echo $str; endif;
<?php if($result_sender2):
$count = 0;
foreach($result_sender2 as $row_sender2):
echo $row_sender2->fname;
if ($count < count($result_sender2)) {
echo ',';
}
$count++;
endforeach;
endif;
?>