Best way in foreach

Author Message

Børge Warvik

Thursday 22 February 2007 2:17:55 am

Hi

What is the best way to get the last item in a foreach loop? I've been doing this with an index variable that increases every loop and check agains the array count.

Claudia Kosny

Thursday 22 February 2007 4:59:44 am

Hi Borge

This depends a bit on where you need the last item. If you just need the last item in an array (without doing the loop) the array operator extract_right might be what you are looking for.
If you loop anyway and need the last item outside of the loop, you could def a variable outside the loop and set it to the current item within the loop. I am not sure how good this is in regards to performance as I don't know what the template language is doing when setting an variable. In PHP this would be alright as it just uses references.
If you need to know the last item within the loop the way you are doing it sounds alright.If your array is numerically indexed you can use the $index in {foreach $array as $index => $value} as iteration counter so you don't need a separate index variable. Also be careful not to compute the count every time in the loop.

Claudia

Powered by eZ Publish™ CMS Open Source Web Content Management. Copyright © 1999-2014 eZ Systems AS (except where otherwise noted). All rights reserved.