Php 如何获取数组循环中的下一个值?
我有一个数组:Php 如何获取数组循环中的下一个值?,php,arrays,Php,Arrays,我有一个数组: $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循环中的下一个值?如下所示,但请记住,foreach在最后一轮中只打印6个值:) 像这样试试 $test
$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循环中的下一个值?如下所示,但请记住,foreach在最后一轮中只打印6个值:) 像这样试试
$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>';
}
$test=数组(1,2,3,4,5,6);
$len=计数($test);
foreach($testas$index=>$value){
如果($test[$index+1]!=''&$test[$index]!='')
回显$value.$test[$index+1]。
;
}
您可以记住最后一个值并以这种方式工作:
$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'
);
试试这个代码
$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];
}
}
试试这个
<?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);
}
?>
它将在最后一轮中生成
未定义的偏移量
。确切地说,这就是我说的上一轮的原因。但我想这是为了其他目的,所以是的。$test=array(1,2,3,4,6,5,6)代码>很抱歉。请参见我的编辑一次$test=array(1,2,3,4,6',,5,6)
在foreach
中如何获得空值..?您有很多有效答案。你可以考虑接受一个。此外,向上投票也是一件好事。你不必烤蛋糕。
<?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