問題描述
我正在使用一些參數編寫 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 循環時查找數組的最后一個元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!