Question

I am writing my own Joomla component (MVC), its based heavily on the newsflash module, because I want to display the latest 5 content items in a sliding tabbed interface, all the hard work is done, but I am having real difficult getting content out of the for loop.

Here is the code I have so far default.php

<ul id="handles" class="tabs">
    <?php for ($i = 0, $n = count($list); $i < $n; $i ++) :
            modSankeSlideHelper::getTabs($list[$i]);
     endfor; ?>                
<li class="end"></li>
</ul>

helper.php

function getTabs(&$item)
{
    global $mainframe;

    $item->created     = $item->created;

    list($year, $month, $day) = split("-", $item->created);
    $tabdate = date('d\/m\/y', mktime(0, 0, 0, $month, $day, $year));

    require(JModuleHelper::getLayoutPath('mod_sankeslide', '_tab'));
}

_tab.php

<li><a href="#tab"><span><?php echo 'Shout ' . $tabdate; ?></span><b></b></a></li>

The first item needs to have different value and a class item added to the a: item, so I need to be able to identify which is the first item and do something during that loop.

I tried to use if $i = 0 else statement in the default.php, but it resulted in a page timeout for some reason!

Any ideas?

Was it helpful?

Solution

You said, you tried if $i = 0, the comparison operator in PHP is ==, with your if you have an endless loop, because in each iteration you assign 0 to $i, and it never reaches $n, you should do inside your loop:

if ($i == 0){
  // First Item here...

}else{
  // Other Items...

} 

OTHER TIPS

I think @CMS is correct.

You might also want to think about handling the first item outside the loop and letting the loop handle the rest of the items. This way you don't have to make the check on each pass through the loop.

If you're using a plain for loop, I'd recommend just acting on the 1st item and then looping through the rest as tvanfosson said. It's slightly faster and potentially easier to read...

doSomethingWithFirst($list[0]);

for ($i = 1; $i < count($list); $i++) {
    doSomethingWithTheRest($list[$i]);
}

I tend to use foreach over for to loop over arrays, in which case, I would use a "firstDone" var, like so:

$bFirstTime = true;
foreach($list as $item) {
    if ($bFirstTime) {
        doSomethingWithFirst($item);
        $bFirstTime = false;
    } else {
        doSomethingWithTheRest($item);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top