开发者

Elegant Method of Inserting Code Between Loops

开发者 https://www.devze.com 2023-01-03 22:46 出处:网络
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,

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?


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.


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.


A trick I use sometimes:

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

        $prefix = '<between code>';
    }
}


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

精彩评论

暂无评论...
验证码 换一张
取 消