我有这个阵列:
$test = array(1,2,3,4,5,6);
foreach($test as $index => $value){
echo $value . $next;
// how to get the next one after the $value ??
}
所以我的显示应该是:
1 2
2 3
3 4
..
..
如何在foreach循环中获得下一个值?
答案 0 :(得分:2)
如下所示,但请记住,你的foreach将在最后一轮打印6只:)
$test = array(1,2,3,4,5,6);
foreach($test as $index => $value){
echo $value . $test[$index+1];
}
答案 1 :(得分:0)
试试这个
$test = array(1,2,3,4,5,6);
$len = count($test);
foreach($test as $index => $value){
if($test[$index+1] != '' && $test[$index] != '')
echo $value . $test[$index+1].'<br>';
}
答案 2 :(得分:0)
你可以记住最后一个值并以这种方式工作:
$test = array(1,2,3,4,5,6);
$last = null;
foreach($test as $index => $next){
if(!is_null($last)) {
echo $last . $next;
}
$last = $next;
}
即使您的索引不是数字,也可以使用,即如果它是:
array(
'Peter' => 'Jackson',
'Steve' => 'McQueen',
'Paul' => 'McCartney',
'April' => 'Ludgate'
);
答案 3 :(得分:0)
试试这段代码
$test = array(1,2,3,4,5,6);
foreach($test as $index => $value){
if(end($test) == $test[$index+1]) {
echo $value . $test[$index+1];
break;
}
else {
echo $value . $test[$index+1];
}
}
答案 4 :(得分:0)
试试这个
<?php
$test = array(1,2,3,4,5,6);
foreach($test as $value)
{
echo $value;
// We have advanced our array pointer. So next is already current
$next = current($test);
// If there is no next, it will return FALSE
if($next)
echo ' '.$next.'<br />';
// Advance array pointer by one
next($test);
}
?>
输出
1 2
2 3
3 4
4 5
5 6
6