Jump to content

create table function


doddsey_65

Recommended Posts

Im messing around with functions and arrays but cant seem to get this to work. It basically creates a simple table with the parameters you specify. The array however doesnt go into the table properly.

 

function asf_create_table($rows, $cols, $border=1, $padding=5, $td_border=1, $contents)
{
$table = "<table style=\"border: {$border}px solid; padding:{$padding}px;\">";

for ($t_rows=0; $t_rows<$rows; $t_rows++)
{
	$table .= "<tr>";
}

for ($t_cols=0; $t_cols<$cols; $t_cols++)
{
	for ($i=0; $i<$cols; $i++)
	{
		$table .= "<td style=\"border: {$td_border}px solid;\">";
		$table .= $contents[$i];
		$table .= "</td>";
	}
}

for ($t_rows=0; $t_rows<$rows; $t_rows++)
{
	$table .= "</tr>";
}


$table .= "</table>";

echo $table;
}

 

$t_contents = array("Cell 1", "Cell 2", "Cell 3", "Cell 4");

asf_create_table("4", "4", "1", "5", "1", $t_contents);

 

instead of 4 cells each with Cell # in them i get 16 cells with the cell #. the 4 displayed 4 times.

Link to comment
Share on other sites

table structure logic appears to be off.

 

this might be closer:

 

for ($t_rows=0; $t_rows<$rows; $t_rows++) {
$table .= "<tr>";

for ($t_cols=0; $t_cols<$cols; $t_cols++)
{
	for ($i=0; $i<$cols; $i++)
	{
		$table .= "<td style=\"border: {$td_border}px solid;\">";
		$table .= $contents[$i];
		$table .= "</td>";
	}
}

$table .= "</tr>";
}

Link to comment
Share on other sites

Try this

<?php
function asf_create_table($rows, $cols, $border = 1, $padding = 5, $td_border = 1, $contents) {
$table = '<table style="border:'.$border.'px solid; padding:{'.$padding.'}px;">';

for($t_rows = 0; $t_rows < $rows; $t_rows ++) {
	$table .= '<tr>';

	for($i = 0; $i < $cols; $i ++) {
	$table .= '<td style="border: '.$td_border.'px solid;">';
	$table .= $contents [$i];
	$table .= '</td>';
    }
    $table .= '</tr>';
}
    $table .= '</table>';
echo $table;

}

$t_contents = array ('Cell 1', 'Cell 2', 'Cell 3', 'Cell 4' );
asf_create_table ( '4', '4', '1', '5', '1', $t_contents );
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.