views:

166

answers:

6

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?

+7  A: 

One method is by using substr

$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");

$output = "";
foreach($array as $i=>$k)
{
    $output .= $i.'-'.$k.',';
}

$output = substr($output, 0, -1);

echo $output;

Another method would be using implode

$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");

$output = array();
foreach($array as $i=>$k)
{
    $output[] = $i.'-'.$k;
}

echo implode(',', $output);
Brad F Jacobs
thank you for your help
Bastien
+11  A: 

Alternatively you can use the rtrim function as:

$result = '';
foreach($array as $i=>$k) {
    $result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
codaddict
Yea, forgot about the trimming. +1
Brad F Jacobs
I like this one better, thanks.
Bastien
too bad php doesn't support `unset($result[strlen($result)-1])`. It would be so nice...
nikic
@NullUserException: Hum, but you can do `string[0] = 'a'`. So you *can* change them. Only unsetting string offsets isn't possible. This doesn't make sense to me, because strings support all array operations (`offsetGet`, `offsetSet`, `offsetExists`) apart from `unset` (`offsetUnset`).
nikic
@niki I wouldn't call unsetting an arbitrary offset an array operation. If it's the last one, yeah; but by the principle of least astonishment you wouldn't want it to support unsetting the last element but not the other ones.
NullUserException
@Daniel k: What would you call it instead? It is one of the operations the `ArrayAccess` interface defines. And these imho are the array operations ;)
nikic
@niki The problem is that PHP arrays are hashmaps, but the underlying implementation of PHP strings is (AFAIK) a character array (eg: a "real" array)
NullUserException
@NullUserException: Yes, you are right, the underlying implementation is different. Still I would expect that all operations on an array are also available for strings, because strings are only a special form of arrays ;)
nikic
@niki Well, I usually just do `substr($str, 0, -1)` if I ever need to remove the last character.
NullUserException
@NullUserException: Well, I do that, too, because there isn't another possibility. But I would like unsetting more, because in this case PHP wouldn't need to copy the whole string to a new chunk of memory ;)
nikic
@niki But that's exactly the point; if you unset an arbitrary element of a real array you *will* have to copy the whole string to a new chunk of memory (unless it's the last element)
NullUserException
@NullUserException: The "unless" isn't uncommon ;) Furthermore, depending on the implementation, you don't need to copy the whole string. For example you could decrement the length property of the string and move all characters down starting from a particular index. That's still faster then copying everything.
nikic
A: 

Hello Bastien,

try this code after foreach condition then echo $result1

$result1=substr($i, 0, -1);

Ravi
+1  A: 

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:

$first = true;
$result = "";
foreach ($array as $i => $k) {
  if (!$first) $result .= ",";
  $first = false;
  $result .= $i.'-'.$k;
}
echo $result;

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.

SPIRiT_1984
How is it a sign of bad programming style? Would you mind elaborating on that for all of us? As far as I can see it does not hinder the performance. I can understand the clarity part, but at the same time it is not hard to read up on what substr does to figure it out. Thanks!
Brad F Jacobs
IMHO, every tool should be used appropriately in programs, and it is NOT substr purpose to serve for string concatenation, it was designed for other issues. Besides, this code with substr looks clear only then it's in one place. If there many fragments like this, the code turns into unreadable. Therefore in our project we changed to normal concatenation, and also made a special function for that. Now the part of project that's dealing with strings is much more readable.
SPIRiT_1984
A: 

I always use this method:

$result = '';
foreach($array as $i=>$k) {
    if(strlen($result) > 0) {
        $result .= ","
    }
    $result .= $i.'-'.$k;
}
echo $result;
serg
Bad idea to use strlen for this. See Joel Spolsky "Back to basics" article in order to see why. Just use a boolean flag in order to perform such check, because in worst case (array has N elements - single characters) you will end up with O(N^2) complexity.
SPIRiT_1984
In general, don't use string functions in order to achieve some effect, that can be easily achieved by simple programming tricks (the same is true for using substr in order to get rid of last comma - it's better not to generate the last comman at all).
SPIRiT_1984
+8  A: 

I dislike all previous recipes.

Php is not C and has higher-level ways to deal with this particular problem.

I will begin from the point where you have an array like this:

$array = array('john-doe', 'foe-bar', 'oh-yeah');

You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.

Now you need to generate a CSV string from this array, it can be done like this:

echo implode(',', $array);
jedi_coder
This approach's benifit that we can change the delimiter easier. Moreover, you can explode the string to array later similar to this.Not sure about performance drawback
thethanghn
+1 for the cleaner approach.
nikic
I like this one better too. Don't loop if you don't have to.
Powertieke
+1, so much better than the rest..
st0le
Apparently you didn't even read *all previous recipes*, cause this was already suggested by premiso.
captaintokyo
It was suggested by me, however I did not use the `array_map` function, but thanks captaintokyo. @Powertieke, it does loop, as `array_map()` would have to loop across the data. I took that the array the OP posted was just a demonstration of his data he got else where.
Brad F Jacobs