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.

eZ debug

Timing: Jan 19 2025 00:14:25
Script start
Timing: Jan 19 2025 00:14:25
Module start 'layout'
Timing: Jan 19 2025 00:14:25
Module start 'content'
Timing: Jan 19 2025 00:14:25
Module end 'content'
Timing: Jan 19 2025 00:14:25
Script end

Main resources:

Total runtime0.0226 sec
Peak memory usage2,048.0000 KB
Database Queries3

Timing points:

CheckpointStart (sec)Duration (sec)Memory at start (KB)Memory used (KB)
Script start 0.00000.0093 587.9141152.6250
Module start 'layout' 0.00930.0050 740.539139.4297
Module start 'content' 0.01430.0060 779.968889.2891
Module end 'content' 0.02020.0023 869.257830.3047
Script end 0.0225  899.5625 

Time accumulators:

 Accumulator Duration (sec) Duration (%) Count Average (sec)
Ini load
Load cache0.002712.1111140.0002
Check MTime0.00114.8472140.0001
Mysql Total
Database connection0.00177.678810.0017
Mysqli_queries0.004318.908330.0014
Looping result0.00000.163610.0000
Template Total0.00198.410.0019
Template load0.00104.365710.0010
Template processing0.00093.980410.0009
Override
Cache load0.00062.838010.0006
General
dbfile0.00031.173080.0000
String conversion0.00000.045440.0000
Note: percentages do not add up to 100% because some accumulators overlap

Templates used to render the page:

UsageRequested templateTemplateTemplate loadedEditOverride
1print_pagelayout.tpl<No override>extension/community/design/community/templates/print_pagelayout.tplEdit templateOverride template
 Number of times templates used: 1
 Number of unique templates used: 1

Time used to render debug report: 0.0003 secs