请帮我把这个伪代码翻译成真正的PHP代码:
foreach ($arr as $k => $v)
if ( THIS IS NOT THE LAST ELEMENT IN THE ARRAY)
doSomething();
Run Code Online (Sandbox Code Playgroud)
编辑:数组可能有数字或字符串键
Ibr*_*mar 123
你可以用PHP的结尾()
$array = array('a' => 1,'b' => 2,'c' => 3);
$lastElement = end($array);
foreach($array as $k => $v) {
echo $v . '<br/>';
if($v == $lastElement) {
// 'you can do something here as this condition states it just entered last element of an array';
}
}
Run Code Online (Sandbox Code Playgroud)
UPDATE1
正如@Mijoja指出的那样,如果你在数组中多次使用相同的值,那么上面可能会有问题.下面是它的修复.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
//point to end of the array
end($array);
//fetch key of the last element of the array.
$lastElementKey = key($array);
//iterate the array
foreach($array as $k => $v) {
if($k == $lastElementKey) {
//during array iteration this condition states the last element.
}
}
Run Code Online (Sandbox Code Playgroud)
UPDATE2
我发现@onteria_的解决方案比我回答的更好,因为它没有修改数组内部指针,我正在更新答案以匹配他的答案.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 2);
// Get array keys
$arrayKeys = array_keys($array);
// Fetch last array key
$lastArrayKey = array_pop($arrayKeys);
//iterate array
foreach($array as $k => $v) {
if($k == $lastArrayKey) {
//during array iteration this condition states the last element.
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢@onteria_
Ric*_*ant 21
这总是对我有用
foreach($array as $key => $value) {
if (end(array_keys($array)) == $key)
// Last key reached
}
Run Code Online (Sandbox Code Playgroud)
编辑30/04/15
$last_key = end(array_keys($array));
reset($array);
foreach($array as $key => $value) {
if ( $key == $last_key)
// Last key reached
}
Run Code Online (Sandbox Code Playgroud)
避免@Warren Sergent提到的E_STRICT警告
$array_keys = array_keys($array);
$last_key = end($array_keys);
Run Code Online (Sandbox Code Playgroud)
ont*_*ia_ 12
$myarray = array(
'test1' => 'foo',
'test2' => 'bar',
'test3' => 'baz',
'test4' => 'waldo'
);
$myarray2 = array(
'foo',
'bar',
'baz',
'waldo'
);
// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
Run Code Online (Sandbox Code Playgroud)
由于对它array_pop创建的临时数组的工作array_keys根本不会修改原始数组.
$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz
Run Code Online (Sandbox Code Playgroud)
小智 5
为什么不使用这种非常简单的方法:
$i = 0; //a counter to track which element we are at
foreach($array as $index => $value) {
$i++;
if( $i == sizeof($array) ){
//we are at the last element of the array
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93250 次 |
| 最近记录: |