在关联数组中查找最后一对

Chr*_*ris 2 php arrays associative-array

我正在使用foreach循环关联数组.我希望能够检查正在处理的键值对是否是最后一个,所以我可以给它特殊的处理.我有什么想法可以做到最好吗?

foreach ($kvarr as $key => $value){
   // I'd like to be able to check here if this key value pair is the last
   // so I can give it special treatment
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*vic 7

这很简单,没有柜台和其他'黑客'.

foreach ($array as $key => $value) {

   // your stuff

   if (next($array) === false) {
      // this is the last iteration
   }
}

请注意,您必须使用===,因为该函数next()可能返回一个非布尔值,其值为false,例如0或""(空字符串).


Tam*_*man 5

我们不需要使用foreach迭代数组,我们可以使用end(),key()和current()php函数来获取最后一个元素并获取它的键+值.

<?php

$a = Array(
  "fruit" => "apple",
  "car" => "camaro",
  "computer" => "commodore"
);

// --- go to the last element of the array & get the key + value --- 
end($a); 
$key = key($a);
$value = current($a);

echo "Last item: ".$key." => ".$value."\n";

?>
Run Code Online (Sandbox Code Playgroud)

如果要在迭代中检查它,end()函数仍然有用:

foreach ($a as $key => $value) {
    if ($value == end($a)) {
      // this is the last element
    }
}
Run Code Online (Sandbox Code Playgroud)