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
https://forums.phpfreaks.com/topic/190531-critique-on-a-php-function-please/
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 :-)

<?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)));
?>

Archived

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.