Reputation: 668
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?
Upvotes: 2
Views: 157
Reputation: 55936
I think you're looking for the [implode][0] 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. [0]: https://www.php.net/manual/en/function.implode.php
Upvotes: 3
Reputation: 70460
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
}
Upvotes: 0
Reputation: 49078
A trick I use sometimes:
function echoWithBreaks($array){
$prefix = '';
foreach($array as $item){
echo $prefix;
//Echo item
$prefix = '<between code>';
}
}
Upvotes: 0
Reputation: 11515
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:
$i > 0
rather than $i < count($array) - 1
.join
or implode
.Upvotes: 1