sukovanej
sukovanej

Reputation: 688

PHP - effective way to determine last loop in foreach

Whenever I have to determine if currect loop in foreach cycle is the last one, i use something like this:

<?php
$i = count($myArray);
foreach ($myArray as $item) {
    /** code goes here... */
    $i--;
    if ($i == 0) {
        /** something happens here */
    }
}
?>

Typically this could by done very easily in templating systems (such as Latte, Smarty, etc...) by knowing the cycle variables (first, last,...). And my question: Is there a similar functionality in PHP?

The key is that you have to create the $i variable, then increase it and check the value. I just want to know if there exists a simpler solution to make my life a little bit easier. :)

Upvotes: 5

Views: 15435

Answers (2)

Dhara Parmar
Dhara Parmar

Reputation: 8101

You find the last item by checking if ($item === end($myArray)) {}

foreach($myArray as $key => $item) {
   echo $item."<br />";
   end($myArray);
   if ($key === key($myArray)) {
      echo 'LAST ELEMENT!';
   }
}

Upvotes: 0

phreakv6
phreakv6

Reputation: 2165

Use this within your foreach for checking if the item is the last item.

if ($item === end($myArray)) {
    // Last item
}

For checking if the item is the first item

if ($item === reset($myArray)) {
    // First item
}

Upvotes: 11

Related Questions