tags:

views:

80

answers:

4

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?

+2  A: 

I think you're looking for the implode function.

Then just echo the imploded string.


The only more elegant i can think of making that exact algorithm is this:

function implodeEcho($array, $joinValue)
{
   foreach($array as $i => $val)
   {
      if ($i != 0) echo $joinValue;
      echo $val;
   }
}

This of course assumes $array only is indexed by integers and not by keys.

Aren
That would work beautifully if I just needed to insert something between individual words or lines.I need to separate large blocks of code, however - and imploding large chunks of HTML around a code chunk of indeterminate length sounds very messy. My apologies if it wasn't clear from the question that I'm working with blocks of HTML.
DeathMagus
Updated my response.
Aren
Interesting update. That may be just what I need. Thanks!
DeathMagus
+1  A: 

Unfortunately, I don't think there is any way to do that with foreach. This is a problem in many languages.

I typically solve this one of two ways:

  1. The way you mention above, except with $i > 0 rather than $i < count($array) - 1.
  2. Using join or implode.
zildjohn01
Your first solution is quite helpful. Thanks.
DeathMagus
A: 

A trick I use sometimes:

function echoWithBreaks($array){
    $prefix = '';
    foreach($array as $item){
        echo $prefix;
        //Echo item

        $prefix = '<between code>';
    }
}
Artelius
No it doesn't!! This works similarly to Wrikken's answer except it does not require an if.
Artelius
Whoops. Sorry - misread. That's a legit solution - though as I told Wrikken, the initialized variable outside the foreach loop makes me cringe a little. Thanks for the response.
DeathMagus
A: 

If more elaborate code then an implode could handle I'd use a simple boolean:

$looped = false;
foreach($arr as $var){
    if($looped){
       //do between
    }
    $looped = true;
    //do something with $var
}
Wrikken
I like this answer in theory, and I played with it for a while before posting, but having to define variables outside the loop makes it less clean than using a simple for loop, in my opinion. Thanks for the input.
DeathMagus