Reply LinkBack Thread Tools Search this Thread
Old 23-09-2007, 09:24   #1 (permalink)
Shiro
shiro
 
Shiro's Avatar
 
Join Date: Aug 2007
Location: Yokohama, Japan
Posts: 2,630
Functions with an unknown number of variables

How do you write a function for which the number of variables to be inputted into it will change each time the function is used. Functions are generally written:

function name ($variable1, $variable2, $variable3) {
do something;
}

In the above function, the variables go up to $variable3, but I want to write a function in which they go up to $variableX where X is determined each time the function is run. Can anyone tell me how to do this? Specifically I am trying to do this in php, but I dont think that matters so much. Thanks guys!
  Reply With Quote
Old 23-09-2007, 09:42   #2 (permalink)
freelancr
Senior Member
 
freelancr's Avatar
 
Join Date: Oct 2006
Posts: 2,175
Use an array, and loop through it.
  Reply With Quote
Old 23-09-2007, 10:27   #3 (permalink)
Shiro
shiro
 
Shiro's Avatar
 
Join Date: Aug 2007
Location: Yokohama, Japan
Posts: 2,630
Thanks, got it working.
  Reply With Quote
Old 23-09-2007, 10:48   #4 (permalink)
d3mcfadden
Senior Member
 
d3mcfadden's Avatar
 
Join Date: Apr 2005
Location: -
Posts: 694
Send a message via AIM to d3mcfadden
use func_num_args() and func_get_args():


PHP Code:
function foo()
{
   
$numargs func_num_args();
   echo 
"this function was passed $numargs";
   
   
$arg_list func_get_args();
   for (
$i 0$i $numargs$i++) {
       echo 
"Argument $i is: " $arg_list[$i] . "<br />\n";
   }
}

foo(123); 
  Reply With Quote
Old 23-09-2007, 14:09   #5 (permalink)
Shiro
shiro
 
Shiro's Avatar
 
Join Date: Aug 2007
Location: Yokohama, Japan
Posts: 2,630
Cool, that one actually works even better for me. When using the other method mentioned earlier in the thread, had to manually set the variables for the array, which meant that I would have had to do that each time I called the function. This method looks like I can skip that step.
  Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search


Contact Us - Web Design Forums - Archive - Top
Search Engine Optimization by vBSEO 3.0.0 RC8