0

I'm trying to create a string from the elements of an array. Here is my array:

$arr = array ( 1 => 'one',
               2 => 'two',
               3 => 'three',
               4 => 'four' );

Now I want this output:

one, two, three and four

As you see in the output above, default seperator is , and last seperator is and.


Well, there is two PHP functions for doing that, join() and implode(). But none of them isn't able to accept different separator for last one. How can I do that?

Note: I can do that like this:

$comma_separated = implode(", ", $arr);
preg_replace('/\,([^,]+)$/', ' and $1', $comma_separated);

Online Demo


Now I want to know is there any solution without regex?

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
  • What's wrong with my solution *(using regex)*? ... Actually that's a good question, But my solution sometimes fails. When the last value of array be containing comma. – Shafizadeh Mar 26 '16 at 13:39

2 Answers2

2

Try this:

$arr = array ( 1 => 'one',
           2 => 'two',
           3 => 'three',
           4 => 'four' );

$first_three     = array_slice($arr, 0, -1); 
$string_part_one = implode(", ", $first_three);  
$string_part_two = end($arr);   

echo $string_part_one.' and '.$string_part_two;  

Hope this helps.

Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
2

You can use foreach and build your own implode();

function implode_last( $glue, $gluelast, $array ){
    $string = '';
    foreach( $array as $key => $val ){
        if( $key == ( count( $array ) - 1 ) ){
            $string .= $val.$gluelast;
        }
        else{
            $string .= $val.$glue;
        }
    }
    //cut the last glue at the end
    return substr( $string, 0, (-strlen( $glue )));
}

$array = array ( 1 => 'one',
           2 => 'two',
           3 => 'three',
           4 => 'four' );

echo implode_last( ', ', ' and ', $array );

If your Array starts with Index 0 you have to set count( $array )-2.