Jump to content

Critique on a PHP function please...


RopeADope

Recommended Posts

Hi all, this may be in the wrong forums so mods feel free to move it.  I'm just looking for some critique on this function I wrote.  Keep in mind that I'm a novice ;-)

 

##################################################
#		Creates a Table			 #
##################################################
<?php
$rows=5;
$columns=5;
function createTable($rows,$columns){
echo "<table>";
for($x=0;$x<$rows;$x++){
	echo "<tr>";
	for($i=0;$i<$columns;$i++){
		echo "<td>space</td>";
	}
	echo "</tr>";
}
echo "</table>";
}
?>
<?php createTable($rows,$columns)?>

Link to comment
Share on other sites

I don't know about making it more efficient, but you could add an optional third parameter to suppply a multidimensional array of data and insert it on the fly

 

Thanks for the suggestion.  That's actually what I plan on doing next but I'm not very well versed in arrays.  I'm trying to get it to the point where the table created has prepopulated data from a database and is editable.  I already have a database connector, but would you mind giving an example of how the multidimensional array would work with this?  A link works as well if you have one :-)

Link to comment
Share on other sites

<?php
$rows=5;
$columns=5;
function createTable($rows,$columns,$array){
echo "<table>";
for($x=0;$x<$rows;$x++){
	echo "<tr>";
	for($i=0;$i<$columns;$i++){
		echo "<td>$array[$x][$i]</td>";
	}
	echo "</tr>";
}
echo "</table>";
}
?>

You also have to check if the array is multidimensional or not.

A more efficient is not sending the rows and columns and using foreach instead.

 

<?php
function createTable($array){
echo "<table>";
foreach($array as $firstkey){
	echo "<tr>";
	foreach($firstkey as $value){
		echo "<td>$value</td>";
	}
	echo "</tr>";
}
echo "</table>";
}
/*Demo*/
createTable(array(array('John','24','Washington'),array('Frank','26',''NYC)));
?>

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.