In: Computer Science
Write a script that will output a table where the rows and cells are labeled. The script should be versatile, so one could easily change the number of rows and cells the script should output. For this exercise have the script create a table with 15 rows and 5 cells. Refer to the tables lesson for information on how to create a table. You need to write all the PHP functionality above the doctype and display the resulting HTML string via a variable in the echo statement within the body element
step-1 : Define two variables 'row_count' and 'col_count' two hold
the number of rows and cells in the table.The number of rows and
cells in the table ,can easily be changed by changing the values of
the variables 'row_count' and 'col_count' .
step-2 : Initialize the variable 'table' with a null string. The variable 'table' holds the output string ,ie the table to be displayed.
step-3 : Check whether the variable 'row_count' is greater than zero and append the html tag '<table>' .Also append '<tr>' tag by using a for loop to generate the required number of rows(row_count)
step-4 : Check whether the variable 'col_count' is greater than zero and append the html tag '<td>' and the label of the cell by using a for loop to generate the required number of cells(col_count)
step-5: Output the table in the body section using an echo statement.The table contains the specified number of rows and columns and each cell is labelled as 'cell' followed by row number and column number.The row number and column number are seperated by a coma(,).
The code is given below,
<?php
$row_count = 15 ;
$col_count = 5 ;
$table = '' ;
if ( $row_count > 0) {
$table .= '<table>' ;
for($i = 1; $i <= $row_count; $i++){
$table .= '<tr>' ;
if ($col_count > 0) {
for ($k=1; $k <=
$col_count ; $k++) {
$table .=
'<td>'.' cell '.$i.','.$k.'</td>' ;
}
}
$table .= '</tr>' ;
}
$table .= '</table>' ;
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
td {
border: 1px solid black;
width: 100px;
}
</style>
<title></title>
</head>
<body>
<?php echo $table; ?>
</body>
</html>
Please refer to the screenshot of the code to understand the indentation of the code.
0) { $table" src= "https://media.cheggcdn.com/coop/e03/e03adfc2-44e1-426c-82df-4a86d8221111/1601874500405_code-table.png" style="height:617px;width:705px;" />
The output of the code is shown below,