Sometimes it's necessary to add a string not just between the items, but before or after too, and proper handling of zero items is also needed.
In this case, simply prepending/appending the separator next to implode() is not enough, so I made this little helper function.
<?php
function wrap_implode( $array, $before = '', $after = '', $separator = '' ){
if( ! $array ) return '';
return $before . implode("{$after}{$separator}{$before}", $array ) . $after;
}
echo wrap_implode(['path','to','file.php'], '/');
$pattern = '#'. wrap_implode([4,2,2], '\d{', '}', '[-.]') .'#';
echo $pattern, "\n"; echo preg_replace( $pattern, '[REDACTED]', 'The UFO appeared between 2012-12-24 and 2013.01.06 every night.');
echo wrap_implode(['line','by','line'], '<b>', '</b>', '<br> ');
echo wrap_implode( ['<a href="">Menu Item 1</a>', '<a href="">Menu Item 2</a>',],
"<li>", "</li>\n",
"<li> | </li>\n",
);
?>