php foreach怎么判断最后一个,在PHP中使用foreach循环时查找数组的最后一个元素

当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);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值