Using next in foreach loop

2019-05-07 15:23发布

I am looping through an array using foreach.

In a particular situation I need to know the value of the next element before iteration comes to that(like a prediction) element. For that I am planning to use the function next().

In documentation I just noticed that next() advances the internal array pointer forward.

next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one.

If so will it affect my foreach loop?

2条回答
看我几分像从前
2楼-- · 2019-05-07 15:35

It will not affect your loop if you use it in this way

<?php

$lists = range('a', 'f');

foreach($lists as &$value) {
   $next = current($lists);
   echo 'value: ' . $value . "\n" . 'next: ' . $next . "\n\n";
}

OUTPUT

value: a next: b

value: b next: c

value: c next: d

value: d next: e

value: e next: f

value: f next:

查看更多
▲ chillily
3楼-- · 2019-05-07 15:51

Try this code:

$a=$array();
foreach($a as $key=>$var)
{
   if(isset($a[$key+1]))
      echo $a[$key+1];//next element
}
查看更多
登录 后发表回答