永恆火焰
永恆火焰

Reputation: 31

Different css styling for last element of a php array

When looping through an array how can I create a different css div style for the last element to be output in my array.

for($i=0;$i<=count($productid);$i++){if($productrank[$i]>0 ){

<? if (($productid[$i] % 2 ) && !( last element of array){ echo '<div class="centerBoxContentsFeatured centeredContent back  vLine " style="width:50%;">';}
else { echo '<div class="centerBoxContentsFeatured centeredContent back " style="width:50%;">';} ?>

Upvotes: 2

Views: 857

Answers (3)

Cl&#233;ment Malet
Cl&#233;ment Malet

Reputation: 5090

Just check if it is the last $productid

for(...)
{
    if ($i === (count ($productid) - 1))
        // Last one -> special CSS
    }
}

Also, DO NOT use count() in a FOR loop if you don't really have to. Just assign a value BEFORE and use it :

$count_temp  = count ($productid);
for ($i = 0; $i < $count_temp; ++$i)

And use this $count_temp again if the IF statement to check if it's the last element


Answer to comment :

How would this same method get the first element?

if ($i === 0)

Or

// Special CSS for $i = 0
// Start loop at 1 instead of 0
for ($i = 1; $i < $count_temp; ++$i)

Upvotes: 2

Jason McCreary
Jason McCreary

Reputation: 72991

You can do this purely with CSS using :last-child. It is supported by all modern browsers.

div.centerBoxContentsFeatured:last-child {
    /* special styles for last */
}

See it in action: http://jsfiddle.net/9y93j/1/

Upvotes: 1

schoash
schoash

Reputation: 166

Like this:

if($productid[$i] ==  $productid[count($productid)-1]){
    //last element code here
} elseif (($productid[$i] % 2 ){
   //even row code here
} else {
   //odd row code here
}

Upvotes: 0

Related Questions