Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.
In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:
The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.
Alternatively you can use the
rtrim
function as:see this example you can easily understand
try this code after foreach condition then echo $result1
this would do:
Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.