Different css styling for last element of a php array

前端 未结 3 1569
遥遥无期
遥遥无期 2021-01-22 13:41

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++){         


        
相关标签:
3条回答
  • 2021-01-22 14:16

    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/

    0 讨论(0)
  • 2021-01-22 14:30

    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
    }
    
    0 讨论(0)
  • 2021-01-22 14:33

    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)
    
    0 讨论(0)
提交回复
热议问题