Find the last element of an array while using a foreach loop in PHP

Vaibhav Kamble picture Vaibhav Kamble · Mar 20, 2009 · Viewed 389.1k times · Source

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;        
}

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.

How do you solve this in PHP?

Answer

Richard Levasseur picture Richard Levasseur · Mar 20, 2009

It sounds like you want something like this:

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

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