你可以使用PHP的end()
$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';
}
}
更新1
正如@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.
}
}
更新2
我发现@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.
}
}
谢谢@onteria_
更新3
正如@CGundlach 指出的那样,PHP 7.3 引入了array_key_last,如果您使用的是 PHP >= 7.3,这似乎是更好的选择
$array = array('a' => 1,'b' => 2,'c' => 3);
$lastKey = array_key_last($array);
foreach($array as $k => $v) {
echo $v . '<br/>';
if($k == $lastKey) {
// 'you can do something here as this condition states it just entered last element of an array';
}
}