php - How can I devote different separator for last item? -


this question has answer here:

i'm trying create string elements of array. here array:

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

now want output:

one, two, 3 , 4 

as see in output above, default seperator , , last seperator and.


well, there 2 php functions doing that, join() , implode(). none of them isn't able accept different separator last one. how can that?

note: can this:

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

online demo


now want know there solution without regex?

you can use foreach , build own implode();

function implode_last( $glue, $gluelast, $array ){     $string = '';     foreach( $array $key => $val ){         if( $key == ( count( $array ) - 1 ) ){             $string .= $val.$gluelast;         }         else{             $string .= $val.$glue;         }     }     //cut last glue @ end     return substr( $string, 0, (-strlen( $glue ))); }  $array = array ( 1 => 'one',            2 => 'two',            3 => 'three',            4 => 'four' );  echo implode_last( ', ', ' , ', $array ); 

if array starts index 0 have set count( $array )-2.


Comments