How do you find the last element of an array while iterating using a foreach loop in php ?

Posted by Vaibhav Kamble on Stack Overflow See other posts from Stack Overflow or by Vaibhav Kamble
Published on 2009-03-20T06:01:27Z Indexed on 2010/06/08 13:52 UTC
Read the original article Hit count: 183

Filed under:
|

I am writing a sql query creator using some parameters. While doing that ,I came across this problem. In java , Its 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 has some different fashion. They have non integer indexes to access arrays. So you must iterate over an array using foreach loop. But it becomes very 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.

How do you solve this problem normally in php ?

© Stack Overflow or respective owner

Related posts about php

Related posts about php5