Reputation: 1630
I have an array $data and I want to print it with foreach ($data as $detail). Thing is that I want inside foreach to print previous and next element. Something like this:
$data = array(1,2,3,4,5,6,7,8);
// foreach result should look like this
8,1,2
1,2,3
2,3,4
3,4,5
4,5,6
5,6,7
6,7,8
7,8,1
Upvotes: 1
Views: 3105
Reputation: 46602
Same result done differently:
<?php
$data = range(1,16);
$count=count($data);
$ret='';
for($i=0;$i<$count;$i++){
$ret.=($i==0)?$data[$count-1].',':$data[$i-1].',';
$ret.=$data[$i].',';
$ret.=($i+1>=$count)?$data[$count-$i-1]:$data[$i+1].'<br>';
}
echo $ret;
?>
Result:
16,1,2
1,2,3
2,3,4
3,4,5
4,5,6
5,6,7
6,7,8
7,8,9
8,9,10
9,10,11
10,11,12
11,12,13
12,13,14
13,14,15
14,15,16
15,16,1
Upvotes: 0
Reputation: 7743
You could go:
$data = array (1,2,3,4,5,6,7,8);
$count = count ($data);
foreach ($data as $key => $current)
{
if (($key - 1) < 0)
{
$prev = $data[$count - 1];
}
else
{
$prev = $data[$key - 1];
}
if (($key + 1) > ($count - 1))
{
$next = $data[0];
}
else
{
$next = $data[$key + 1];
}
echo $prev . ', ' . $current . ', ' . $next . "\n";
Or if brevity is an issue:
$count = count ($data);
foreach ($data as $i => $current)
{
$prev = $data[(($i - 1) < 0) ? ($count - 1) : ($i - 1)];
$next = $data[(($i + 1) > ($count - 1)) ? 0 : ($i + 1)];
echo $prev . ',' . $current . ',' . $next . "\n";
}
Upvotes: 0
Reputation: 23041
<?php
$data = array(1,2,3,4,5,6,7,8);
$count = count($data);
foreach($data as $index => $number)
{
$previous = $data[($count+$index-1) % $count]; // '$count+...' avoids problems
// with modulo on negative numbers in PHP
$current = $number;
$next = $data[($index+1) % $count];
echo $previous.", ".$current.", ".$next."\n";
}
About modulo on negative numbers: http://mindspill.net/computing/cross-platform-notes/php/php-modulo-operator-returns-negative-numbers.html
Upvotes: 5