Re: Variable number of parameters

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Philip Thompson wrote:
On Aug 5, 2008, at 8:58 AM, Daniel Brown wrote:

On Tue, Aug 5, 2008 at 1:40 AM, Philip Thompson <philthathril@xxxxxxxxx> wrote:
Is it possible to grab a variable number of parameters and send the
appropriate amount to another function?

   You can predefine function parameters:

<?php
function example($line1,$line2="There is no line 2.") {
   echo $line1."\n";
   echo $line2."\n";
}

example("This is a test.","This is another test.");
/*
   Returns:
       This is a test.
       This is another test.
*/

example("This is a third test.");
/*
   Returns:
       This is a third test.
       There is no line 2.
*/
?>

   .... but more likely, you're looking for func_get_args().

       http://php.net/func_get_args

Fortunately, I am quite familiar with your example. However, I am more looking for something in which I could send any number of parameters to my own function, grab each one of those individually, and then send them each to another built-in function. Basically, I want to avoid hard-coding this. On top of looking ugly, it's bad practice.

<?php
function myFunction () {
  $args = func_get_args();
anotherFunction ($args[0], $args[1], $args[2], $args[3], $args[4], $args[5]);
  // And continue counting up to a random number where I don't
  // think I'll have more than, say, 10 arguments
}
?>

Of course, even if I did hard-code this nastiness, anotherFunction() would still complain about whatever parameters were not used. So, args 0 and 1 are filled, but 2-5 are not. "Warning! Warning! You can't have args 2 through 5, stoopud!"

Alas, I feel I must take a different approach to solve this problem.

~Philip

Hi Phillip

Why not use a foreach()?

<?php
 function myFunction () {
   $args = func_get_args();
   foreach($args as $arg)
	anotherFunction ($arg);
    }
 }
?>

That way you can send as many arguments as you please, without any ugly hardcoding...

Igor

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux