Jump to content

Count total no of row in a table in PHP


Recommended Posts

Hi I am viewing xls table in php using below code. I want to count the no of row of the table below the line. But its not appearing the result. Result is showing O, but it should be 6. Please have a look & advise.

echo $table ="<table>";   
    while($x<=$connection->sheets[$sheet]['numRows']) {
      echo "\t<tr>\n";
      while($y<=$connection->sheets[$sheet]['numCols']) {
        $cell = isset($connection->sheets[$sheet]['cells'][$x][$y]) ? $connection->sheets[$sheet]['cells'][$x][$y] : '';
        echo "\t\t<td>$cell</td>\n";  
      echo "\t</tr>\n";
 echo "</table>";  
 $count = substr_count($table, "<tr>");
echo "Total rows: ".$count;
echo "</br>";
Link to comment
Share on other sites

Well, let's look at how you are getting the count of rows

$count = substr_count($table, "<tr>");

Ok, so you are using a function to count the number of occurrences of "<tr>" within the variable $table.
Ok, now let's look at where the "<tr>" values are being added to the $table variable. Oh wait, they aren't! For some unexplained reason the output is being echo'd instead of appended to the $table variable. in fact, the only place $table is being defined is in the initial definition

echo $table ="<table>";

Why you would echo a value being defined to a variable makes no sense.
So, let's start over. Only define/append values to $table (do not echo anything). Then, once ALL of the content has been defined, THEN echo the variable to the page. As for counting the rows, having to use substr_count() after you have defined the content is not how I would suggest doing it. Instead, create a counter before the loop $count = 0;, then increment the counter within the loop $count++;.
Barand's suggestion would obviously work for this particular scenario as would counting the "<tr>" instances. But, I suggest adding a loop counter for a couple of reasons. 1) If you were to add a header row or other "row" content to the output, them the number of "<tr>" tags might not be the correct number. 2) When processing an input source (such as this spreadsheet) you may have a need to reject some rows of data for the output. By having a loop counter inside the loop you can ensure rejected rows do not increment the counter.



Why are you outputting tab characters inside the cells?

I do this as well. I also include line breasks in the output: \n. It makes debugging the generated HTML code much, much simpler. E.g.



Link to comment
Share on other sites


This topic is now archived and is closed to further replies.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.