10 December 2015

Repeat a string in PHP with iteration counter - quick and easy function

When you're working through some complex program logic, low level code like manipulating strings is a distraction to write and worse, when you come back to it six months later, it makes your code look long and daunting to get back into. With this in mind, I always try to wrap low level code in re-usable functions.

Here's one such handy little function which works just like PHP's native str_repeat but it will include the iteration count in the string itself and do some cleaning at the end. This is perfect for generating numbered lists, sql queries and a bunch of other uses.

//Repeat a string with iterator
function strRepeat( $string, $count=1, $replace='', $trim='' ){
 $res = '';
 for($i=1; $i<=$count; $i++) $res .= str_replace($replace,$i,$string);
 return $trim ? trim($res,$trim) : $res;

echo strRepeat('testX,',5,'X',',');

// outputs: "test1,test2,test3,test4,test5" //note the final , is trimmed away, ready for use

Cron Design Studio: Dublin based web design & software development