Welcome Guest, Not a member yet? Register   Sign In
[Solved] First element of a foreach loop
#1

[eluser]laegnur[/eluser]
Hi.

I'm new to CodeIgniter.

In a view I have the next code

Code:
<?php
  foreach ($a as $b)
  {
?>
<?php
    echo '<div>'.$b->field1.'-'.$b->field2.'</div>'."\n";
?&gt;
&lt;?php
  }
?&gt;


How can I identified the first "foreach" element, to apply a special css class to it.


Sorry for my bad english...

Edit: Thanks pistolPete and tomcode for your answers.
#2

[eluser]pistolPete[/eluser]
How about this:
Code:
$first = TRUE;
foreach ($a as $b)
{
    if($first)
    {
        echo '<div id="first">'.$b->field1.'-'.$b->field2.'</div>'."\n";
        $first = FALSE;
    }
    else
    {    
        echo '<div>'.$b->field1.'-'.$b->field2.'</div>'."\n";
    }
}
#3

[eluser]tomcode[/eluser]
Even shorter :
Code:
$first = ' id="first"';
foreach ($a as $b)
{
    echo '<div' .$first .'>'.$b->field1.'-'.$b->field2.'</div>'."\n";

    if($first != '') $first = '';
}




Theme © iAndrew 2016 - Forum software by © MyBB