問題描述
我正在使用一些參數(shù)編寫 SQL 查詢創(chuàng)建器.在 Java 中,只需通過數(shù)組長(zhǎng)度檢查當(dāng)前數(shù)組位置,就可以很容易地從 for 循環(huán)內(nèi)部檢測(cè)數(shù)組的最后一個(gè)元素.
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 中,它們有非整數(shù)索引來訪問數(shù)組.因此,您必須使用 foreach 循環(huán)遍歷數(shù)組.當(dāng)您需要做出一些決定(在我的情況下,在構(gòu)建查詢時(shí)附加或/和參數(shù))時(shí),這會(huì)成為問題.
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).
我相信一定有一些標(biāo)準(zhǔn)的方法可以做到這一點(diǎn).
I am sure there must be some standard way of doing this.
你如何在 PHP 中解決這個(gè)問題?
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
迭代數(shù)組".
That being said, you don't -have- to iterate over an "array" using foreach
in php.
這篇關(guān)于在 PHP 中使用 foreach 循環(huán)時(shí)查找數(shù)組的最后一個(gè)元素的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!