当toEnd达到0时,表示它在循环的最后一次迭代中。
$toEnd = count($arr);
foreach($arr as $key=>$value) {
if (0 === --$toEnd) {
echo "last index! $value";
}
}
最后一个值在循环后仍然可用,因此如果您只想在循环后将其用于更多内容,则更好:
foreach($arr as $key=>$value) {
//something
}
echo "last index! $key => $value";
如果您不想将最后一个值视为特殊的内部循环。如果您有大型阵列,这应该会更快。(如果在同一作用域内循环后重用数组,则必须先“复制”数组)。
//If you use this in a large global code without namespaces or functions then you can copy the array like this:
//$array = $originalArrayName; //uncomment to copy an array you may use after this loop
//end($array); $lastKey = key($array); //uncomment if you use the keys
$lastValue = array_pop($array);
//do something special with the last value here before you process all the others?
echo "Last is $lastValue", "\n";
foreach ($array as $key => $value) {
//do something with all values before the last value
echo "All except last value: $value", "\n";
}
//do something special with the last value here after you process all the others?
echo "Last is $lastValue", "\n";
并回答您的原始问题“在我的情况下,在构建查询时要追加或/和参数”;这将遍历所有值,然后将它们连接在一起,并在它们之间加上一个“和”字符串,但不要在第一个值之前或最后一个值之后:
$params = [];
foreach ($array as $value) {
$params[] = doSomething($value);
}
$parameters = implode(" and ", $params);