Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find last index of foreach loop in smarty

Tags:

php

smarty

How to get last index value of foreach loop in smarty,i m new for smarty I have used this code but its not working

{foreach from=$cityList key=myId item=i name=foo}
 {$i.location_name}{if $main_smarty.foreach.foo.last}<hr>{else}-{/if}
  {/foreach}

i want that when their is last city name after this its come horizontal line otherwise its like india-USA-Japan- but at last it come Japan-china

In .php i use

<?php
include_once('Smarty.class.php');
$main_smarty = new Smarty;

query to find citylist
$main_smarty->assign('cityList',$cityList);
?>
like image 442
Bhanu Prakash Pandey Avatar asked Jun 25 '10 12:06

Bhanu Prakash Pandey


People also ask

How do you find the last item in foreach?

Use count() to determine the total length of an array. The iteration of the counter was placed at the bottom of the foreach() loop - $x++; to execute the condition to get the first item. To get the last item, check if the $x is equal to the total length of the array. If true , then it gets the last item.

How do you foreach in Smarty?

{foreach} is used to loop over an associative array as well a numerically-indexed array, unlike {section} which is for looping over numerically-indexed arrays only. The syntax for {foreach} is much easier than {section} , but as a tradeoff it can only be used for a single array.


2 Answers

You're looking for this one:

{foreach from=$cityList key=myId item=i name=foo}
    {if $smarty.foreach.foo.last}
        <p>This is the last item from the array!</p>
    {/if}
{/foreach}

As you see, the property you need to check is $smarty.foreach.foo.last where foo is the name of your object.

like image 91
Bogdan Constantinescu Avatar answered Sep 17 '22 12:09

Bogdan Constantinescu


If $arr is the array you passed to the {foreach}, this will do the trick:

{$arr|@end}

In fact, it does not have to be called inside a {foreach}

like image 35
Lukman Avatar answered Sep 19 '22 12:09

Lukman