Elegant Method of Inserting Code Between Loops
Posted
by DeathMagus
on Stack Overflow
See other posts from Stack Overflow
or by DeathMagus
Published on 2010-06-16T23:52:08Z
Indexed on
2010/06/17
0:02 UTC
Read the original article
Hit count: 202
In web development, I often find I need to format and print various arrays of data, and separate these blocks of data in some manner. In other words, I need to be able to insert code between each loop, without said code being inserted before the first entry or after the last one. The most elegant way I've found to accomplish this is as follows:
function echoWithBreaks($array){
for($i=0; $i<count($array); $i++){
//Echo an item
if($i<count($array)-1){
//Echo "between code"
}
}
}
Unfortunately, there's no way that I can see to implement this solution with foreach instead of for. Does anyone know of a more elegant solution that will work with foreach?
© Stack Overflow or respective owner