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


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?

6/8/2016 5:14:21 AM

Accepted Answer

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.

6/10/2012 10:01:40 PM

You could get the value of the last key of the array using end(array_keys($array)) and compare it to the current key:

$last_key = end(array_keys($array));
foreach ($array as $key => $value) {
    if ($key == $last_key) {
        // last element
    } else {
        // not last element

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow