4

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. :)

sukovanej
  • 658
  • 2
  • 8
  • 18
  • 2
    check http://stackoverflow.com/questions/665135/find-the-last-element-of-an-array-while-using-a-foreach-loop-in-php and http://stackoverflow.com/questions/1070244/how-to-determine-the-first-and-last-iteration-in-a-foreach-loop – Saty Jun 08 '16 at 09:13
  • I checked and they're using the solution with $i variable or the (generally) wrong solution with `end()` function - as @nospor mentioned. – sukovanej Jun 08 '16 at 09:24

2 Answers2

10

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
}
phreakv6
  • 2,135
  • 1
  • 9
  • 11
0

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!';
   }
}
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27