1

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
6
  • 1
    what did you try to do? Please post the code who have tried. We will help to complete it Commented Nov 24, 2011 at 10:29
  • Show us the code you have so far. Commented Nov 24, 2011 at 10:29
  • Do you know how to use array indices? Commented Nov 24, 2011 at 10:30
  • also, please explain why in the first item, the previous item is refer to the last item in the array? (should not it be empty?) same problem on the last item Commented Nov 24, 2011 at 10:31
  • 1
    Sounds like a homework problem. Commented Nov 24, 2011 at 10:31

3 Answers 3

5
<?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

Sign up to request clarification or add additional context in comments.

Comments

0

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";
}

1 Comment

This solution assumes an array with numeric index and no holes.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.