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;
}

//EXAMPLE:
echo strRepeat('testX,',5,'X',',');

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

2 comments:

Anonymous said...

We love the fact that you are discussing technology in a very refined manner. The perspective on this issue is very enlightening. Great job. Urban Kreative - website designing and developing company in Nairobi Kenya http://www.urbankreative.com

Meiqing Xu said...

jordan shoes
canada goose jackets uk
hermes handbags
kobe shoes
michael kors uk
ralph lauren
buy red bottoms
louis vuitton handbags outlet
rolex replica watches
christian louboutin outlet
20161228caiyan

Post a Comment

Cron Design Studio: Dublin based web design & software development