-1

I'm trying here to explode the commas and to show the words in this type:

Words included: Word1, Word2, Word3, Word4, Word5 (without the comma at the end)

I've wrote a code:

<?php
$str = "Word1, Word2, Word3, Word4, Word5,";
$array = explode(',', $str);

foreach($array as $var)
{
    echo $var.", ";
}
?>

But then it show's:

Words included: Word1, Word2, Word3, Word4, Word5, (with comma at the end)

How can I remove the last comma?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Apromer
  • 59
  • 2
  • 8

7 Answers7

1

If all you want to do is remove the last comma use substr

$str = substr($str, 0, -1);
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
1

You could also remove the last comma using rtrim():

$array = explode(',', rtrim($str, ','));

But, since you output commas inside your loop you could remove the last one using rtrim() after your loop:

$output = '';
$str = "Word1, Word2, Word3, Word4, Word5,";
$array = explode(',', $str);

foreach($array as $var) {
  $output .= $var . ',';
}
print rtrim($output, ',');
  
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
1

I prefer to use implode in PHP, it will do the same as your for loop and has the ability to define a seperator.

So your code would be

$str = "Word1, Word2, Word3, Word4, Word5,";
$array = explode(',', $str);

//Implode function, you can also set it to return the value to a variable
print implode(", ",$array);
Tom
  • 403
  • 3
  • 14
  • 1
    This would print `Word1,[space][space]Word2,[space][space]Word1,[space][space]Word3,[space][space]Word4,[space][space]Word5,[space]` (double spacing and an extra comma and spaces in the end). – h2ooooooo Feb 05 '15 at 15:13
1

Whenever you iterate through a loop and add , to the end of the string, the final string will have a , on the end of it. To solve this, use implode on an array, rather than appending stuff to a string.

Example:

<?php

$data = 'foo,bar,oof,rab';

$split = explode(',', $data);

$buffer = '';

foreach ($split as $value) {
    $buffer .= $value . ', ';
}

var_dump( $buffer ); // string(20) "foo, bar, oof, rab, "
var_dump( implode(', ', $split)); // string(18) "foo, bar, oof, rab"

DEMO

In your example to also remove empty values, you can simply use preg_split, array_filter and implode:

<?php

$data = 'Word1, Word2, Word3, Word4, Word5,';

// Split on comma and remove empty values
$words = array_filter(preg_split('/\s*,\s*/', $data));

// string(33) "Word1, Word2, Word3, Word4, Word5"
var_dump( implode(', ', $words) ); 

// string(41) "Word1 OR Word2 OR Word3 OR Word4 OR Word5"
var_dump( implode(' OR ', $words) ); 

DEMO

Notice that we can glue it together with whatever we choose.

Why use preg_split instead of explode? It's simple. preg_split with a regex of \s*,\s* will split the string on "any amount of spaces (\s*)" followed by "a comma (,)" followed by "any amount of spaces (\s*)". This means that we can join on eg. . and get Word1.Word2.Word3.Word4.Word5 rather than Word1. Word2. Word3. Word4. Word5 (so essentially we have full control).

h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
1

Your problem is the last , in your string

$str = "Word1, Word2, Word3, Word4, Word5,";
//---------------------------------------^

This causes the explode to create a empty array and your foreach goes through the array for every position, no matter if its filled or not. Also you allways add a , to the end of the string so that's not actually that what you want :)

There are some answere here that suits. But you can also check for empty arrays..

<?php
    $str = "Word1, Word2, Word3, Word4, Word5,";
    $array = explode(',', $str);

    foreach($array as $var)
    {
        if(empty($output)){
            $output = $var;
        }else{
            if(!empty($var))
                $output .= "," . $var;
        }
    }
    echo $output;
?>
Dwza
  • 6,494
  • 6
  • 41
  • 73
  • 1
    You are completly right, but wouldn't it be easier to just use `rtrim()` after the loop? – Cyclonecode Feb 12 '15 at 00:16
  • 1
    indeed, actually since he obviously only want to get rid of the last comma that's all he has to do anyway. `echo rtrim($str,',');` :D I just tried to point this out what he is doing and added a if so make it clear... to code its self is horrible :D – Dwza Feb 12 '15 at 17:06
0

Try:

$str = trim($str,",");

before $array = explode(',', $str);

YyYo
  • 651
  • 5
  • 13
0

The comma's there, because you're telling PHP to output it. You can either use implode() as others have suggested, or make a more complicated loop: Change how you output the comma to be before and dynamically update it, or somehow detect when you're at the END of the loop and suppress its output.

This version does the first option:

$comma = ''; // initially blank

foreach($array as $var) {
    echo $comma, $var;
    $comma = ', ';
}

In other words, only output a comma BEFORE the words on the 2nd and subsequent loop iterations. The first time around the loop, $comma would be blank when you do the output.

Marc B
  • 356,200
  • 43
  • 426
  • 500