A variable number of arguments in a PHP function
Archive - Originally posted on "The Horse's Mouth" - 2009-11-02 06:40:53 - Graham EllisDo you want to vary the number of arguments you pass in to a PHP function?
loadarticles(2,3,6,5,4);
loadarticles(5,7);
Simply declare your function with a minimum of parameters that you need (perhaps zero) and use the func_get_args() function to get you an array of all the parameters. Here's an example:
function loadarticles() {
$abase = array();
database_connect();
$inputs = func_get_args();
foreach ($inputs as $article) {
$row = database_get("select * from mt_entry where entry_id = $article");
$abase[body] .= "<tr><td class=\"pageName\">$row[entry_title]</td></tr>";
$abase[body] .= "<tr><td class=\"bodytext\">$row[entry_text]</td></tr>";
}
return $abase;
}
The func_num_args function can be used to obtain just the number of arguments used to call your current function, and the func_get_arg function to obtain a specific argument by position number.
Although you can write a function to pick up a variable number of arguments, it is usually better programming practice to pass in an array of varying length ... so in other words, I'm advising you to used func_get_args sparingly!