0

I wonder how can i find out last in table with PHP, aka if that is last then i want to apply different style and content to it.

This is part of my code generating table content.

  $content .= '</tr>';

  $totalcols = count ($columns);
  if (is_array ($tabledata))
  {
    foreach ($tabledata as $tablevalues)
    {
      if ($tablevalues[0] == 'dividingline')
      {
        $content .= '<tr><td colspan="' . $totalcols . '" style="background-color:#efefef;"><div align="left"><b>' . $tablevalues[1] . '</b></div></td></tr>';
        continue;
      }
      else
      {
        $content .= '<tr>';
        foreach ($tablevalues as $tablevalue)
        {
          $content .= '<td>' . $tablevalue . '</td>';
        }

        $content .= '</tr>';
        continue;
      }
    }
  }
  else
  {
    $content .= '<tr><td align="center" style="border-bottom: none;" colspan="' . $totalcols . '">No Records Found</td></tr>';
  }

I know there is option to do something like that with jQuery later on, but I don't want to complicate it and just solve it with php at time when i generate table.

ProDraz
  • 1,283
  • 6
  • 22
  • 43

5 Answers5

2

Keep a count:

$count = 1;
foreach ($tablevalues as $tablevalue)
{
    $count++;

    if( $count > count( $tablevalues)) {
        echo "Last td tag is up next! ";
    }
    $content .= '<td>' . $tablevalue . '</td>';
}
nickb
  • 59,313
  • 13
  • 108
  • 143
1

you can execute any code in last loop:

for($i=0;$i<count($tablevalues);$i++)
{
    $tablevalue=$tablevalues[$i];
    $content .= '<td>' . $tablevalue . '</td>';
    if($i==count($tablevalues)-1){ 
        // last loop execution
    }
}
ahoo
  • 1,321
  • 2
  • 17
  • 37
1

here is a somehow trick

foreach ($tablevalues as $k => $tablevalue)
{
  if ($k==count($tablevalues)-1)
  {
    // last td of current row
    $content .= '<td>' . $tablevalue . '</td>';
  }
  else
  {
    $content .= '<td>' . $tablevalue . '</td>';
  }
}

I just hope that your keys of your $tablevalues set match this code.

Keil
  • 222
  • 2
  • 8
0

You should use a for($i = 0; i < count($tablevalues); $i++) {} loop and consider count($tablevalues)-1 to be the last key of your array.

So that $tablevalues[count($tablevalues)-1] is your last <td>.

Shoe
  • 74,840
  • 36
  • 166
  • 272
0

Why dont you use jQuery?It has provisions to do something like that.

techie_28
  • 2,123
  • 4
  • 41
  • 62