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

查看:32
本文介绍了在 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天全站免登陆