Main
Index
Search
Posts
Who's
Online
Log
In

Home: Products: CMS Builder:
Testing for last item in loop

 

 


theclicklab
User

Dec 4, 2011, 10:45 AM

Post #1 of 4 (756 views)
Shortcut
Testing for last item in loop Can't Post

Hi there,

I need to test for the last item in a navbar so i can remove the separator " | ", could not find it in the forum.

Here is the code:


Code
<?php 
// load records
list($pagesRecords, $pagesMetaData) = getRecords(array(
'tableName' => 'pages',
'loadUploads' => '0',
'allowSearch' => '0',
'where' => 'footer_nav ="1"',
'useSeoUrls' => true,
));
?>



Code
<?php foreach ($pagesRecords as $record): ?> 
<a href="<?php echo $record['_link'] ?>"><?php echo $record['name'] ?> </a> |
<?php endforeach ?>


Many thanks
~~~~~~~~~~~~~~~~~~
Jan Dunlop
theClickLab.com
nz.linkedin.com/in/jandunlop
~~~~~~~~~~~~~~~~~~


Jason
Staff / Moderator


Dec 5, 2011, 7:47 AM

Post #2 of 4 (747 views)
Shortcut
Re: [theclicklab] Testing for last item in loop [In reply to] Can't Post

Hi Jan,

One approach would be to put all your menu links into a string and then use the rtrim() function to remove the last | from the string.

For example:


Code
<?php $menu = ""; ?> 
<?php foreach ($pagesRecords as $record): ?>
<?php $menu .= " <a href=\"". $record['_link'] ."\">". $record['name']." </a> |"; ?>
<?php endforeach ?>

<?php $menu = rtrim($menu, "|"); ?>
<?php echo $menu; ?>



Hope this helps
---------------------------------------------------
Jason Sauchuk - Programmer 
interactivetools.com

Hire me! Save time by getting our experts to help with your project.
http://www.interactivetools.com/consulting/ 


Collin
Novice


Dec 5, 2011, 9:04 AM

Post #3 of 4 (742 views)
Shortcut
Re: [theclicklab] Testing for last item in loop [In reply to] Can't Post

What I often do for this is use the 'implode' function:


Code
<?php 

$menuItems = array();
foreach ($pagesRecords as $record){
$menuItems[] = "<a href=" . $record['_link'] . "> " . $record['name'] . "</a>"
}

$menu = implode(' | ', $menuItems);

echo $menu;
?>


http://php.net/manual/en/function.implode.php


(This post was edited by Collin on Dec 5, 2011, 10:04 AM)


theclicklab
User

Dec 5, 2011, 2:24 PM

Post #4 of 4 (730 views)
Shortcut
Re: [Collin] Testing for last item in loop [In reply to] Can't Post

Jason/Collin, fantastic - thanks so much :)
~~~~~~~~~~~~~~~~~~
Jan Dunlop
theClickLab.com
nz.linkedin.com/in/jandunlop
~~~~~~~~~~~~~~~~~~