How to create Functions that Take a variable number of arguments in PHP

Recently I was coding small application in PHP. I wrote simple function that generates the HTML code of table. Here is what I did first

startTable($col, $heading1, $heading2);

Problem with above function was clear I needed something which can very both column and heading without writing 2-3 functions. I know this can be done in ‘C’. So I opened the PHP documentation and I come across this “PHP 4 has support for variable-length argument lists in user-defined functions. This is really quite easy, using the func_num_args(), func_get_arg(), and func_get_args() functions.” :)

So I rewrote my startTable() as follows:


function startTable($allArgs){
	// the number of arguments passed to the function
	$size = func_num_args();

	echo '<table border=1 width=100%><tr>';
	$width=100;
	if ( $size == 2 ) $width=50;

	if ( $size == 3 ) $width=33;

	if ( $size == 4 ) $width=25;

        // iterate through the arguments and add up the numbers
	for ($i = 0; $i < $size; $i++) {

		$colTitle = func_get_arg($i);
		echo "<td width=$width% align=center bgcolor=#BFBFBF>$colTitle</td>";

	}
	echo "</tr>";
}

Basically func_num_args() returns the number of arguments passed to the function and func_get_arg($i) return an item from the argument list. Finally I endup creating addRow as follows:


function addRow($data){

	$size= func_num_args();
	$width=100;
	if ( $size == 2 ) $width=50;

	if ( $size == 3 ) $width=33;

	if ( $size == 4 ) $width=25;

	echo "<tr>";
	for ($i = 0; $i < $size; $i++) {

		$align="";
		$colData = func_get_arg($i);

		$tmp=split("\|","$colData");
		$align = current($tmp);

		$text =  end($tmp);
		if ($align == $text ) $align="left";

		echo "<td width=$width% align=$align>$text</td>";
	}
	echo "</tr>";

}
?>

Author: admin

I like chocolate, gadgets, open source software, photography, traveling and all shades of green colors. I love spending time with fun loving friends and family members. This is my own online journal.

Leave a Reply

Your email address will not be published.