Reputation: 43
I am trying to remove the last comma so that it will look like
1,2,3 instead of 1,2,3,
Here is what I have so far;
<?php
include_once 'header.php';
?>
<div id="content">
Lesson on arrays<br />
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
foreach ($nums as $value) {
echo rtrim($value,",");
}
?>
</div>
<?php
include_once 'footer.php';
?>
Currently with the rtrim command in I am getting back
My 1st array =0123
Thanks for any help
Upvotes: 0
Views: 93
Reputation: 1273
You can use more generic way like following, here comma is attached from second element onwards:
implode
is the quickest way to achieve this as explained in previous answer but if you are using loop
then use below code:
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
$comma = '';
foreach ($nums as $key => $value) {
echo $comma . $value;
$comma = ',';
}
?>
Upvotes: 0
Reputation: 1368
You have two ways you can do with
<?php
$string = "";
$nums = array(0, 1, 2, 3);
echo "My 1st array = ";
foreach ($nums as $value) {
$string .= $value.",";
}
print_r(rtrim($string,','));
?>
<?php
$nums = array(0, 1, 2, 3);
$string_by_implode = implode(',',$nums);
echo "My 1st array = " . $string_by_implode;
?>
Upvotes: 0
Reputation: 21
Why to use foreach loop when you can do it without the loop, by using implode(). implode() function returns a string separated by a "seperater" from the elements of an array.
$nums = array(0, 1, 2, 3);
echo "My 1st array = ";
$str=implode(",",$nums);
echo $str;
This will give you the output as My 1st array = 0,1,2,3
Upvotes: 1
Reputation: 23958
If you must use that setup then use the $key in the foreach to determine if there should be a comma or not.
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
foreach ($nums as $key => $value) {
if($key !=0) echo ",";
echo $value;
}
Upvotes: 0
Reputation: 5731
Instead of for loop you can directly use implode
function.
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
echo implode(',',$nums);
?>
Edit : if you want foreach loop
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
$str='';
foreach ($nums as $value) {
$str.= $value.",";
}
echo rtrim($str,',');
?>
Upvotes: 4
Reputation: 1445
Try this
$myStr = 'planes,trains,automobiles,';
$myStr = trim($myStr, ',');
Output
planes,trains,automobiles
Upvotes: 2