在PHP中使用foreach循环时查找数组的最后一个元素 [英] Find the last element of an array while using a foreach loop in PHP

查看:216
本文介绍了在PHP中使用foreach循环时查找数组的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些参数编写SQL查询创建器.在Java中,仅通过检查当前数组位置和数组长度,就可以很容易地从for循环中检测数组的最后一个元素.

I am writing a SQL query creator using some parameters. In Java, it's very easy to detect the last element of an array from inside the for loop by just checking the current array position with the array length.

for(int i=0; i< arr.length;i++){
     boolean isLastElem = i== (arr.length -1) ? true : false;        
}

在PHP中,它们具有非整数索引来访问数组.因此,您必须使用foreach循环遍历数组.当您需要做出一些决定时(在我的情况下,在构建查询时附加或/和参数),这将成为问题.

In PHP they have non-integer indexes to access arrays. So you must iterate over an array using a foreach loop. This becomes problematic when you need to take some decision (in my case to append or/and parameter while building query).

我确信必须有一些标准的方法来做到这一点.

I am sure there must be some standard way of doing this.

如何用PHP解决这个问题?

How do you solve this in PHP?

推荐答案

听起来您想要这样的东西:

It sounds like you want something like this:

$numItems = count($arr);
$i = 0;
foreach($arr as $key=>$value) {
  if(++$i === $numItems) {
    echo "last index!";
  }
}    

话虽这么说,您不必-必须-在php中使用foreach遍历数组".

That being said, you don't -have- to iterate over an "array" using foreach in php.

这篇关于在PHP中使用foreach循环时查找数组的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆