HomeContactLinks

Passing variable numbers of arguments to functions

By Flib

2009-05-20

Category: PHP

The problem

Recently a visitor in my IRC channel came in with an odd problem. He needed to send a variable amount of arguments to a function. The function wasn't under his control, so he was unable to pass an array to it and parse it within the function itself.

PHP as far as I can tell has no easy way to do this. This short article explains one method to accomplish the task.

The Solution

PHP has a couple of methods within a function for coping with variable numbers of arguments, but no easy way of sending a variable number of arguments.

This can be circumvented by judicious use of PHPs ample string operators and the eval function. Example code is below

<?php $input="one',\"two,three,four"; function dump(){ $numargs=func_num_args(); echo "numargs = $numargs<br /><pre>"; for ($i=0;$i<$numargs;$i++) { var_dump(func_get_arg($i)); } echo '</pre>'; } //prove the output function works as designed dump(1,2,array('foo','bar'),'test'); //produce an argument list $input2=explode(',',$input); $varlist=''; foreach($input2 as $var) { $varlist.='"'.addslashes($var).'",'; } //we have added one too many commas... $varlist=substr($varlist,0,-1); //construct function call $cmd='dump('.$varlist.');'; echo $cmd."\n"; //run it eval($cmd); ?>

I'm sure this isn't the only option, but it seems to me to be the easiest as far as side effects go. As far as security, this script is no different from any other use of the eval function. Be careful what you pass into it, escape any user data and you should be safe enough.

©2009 AskFlib.com

Powered by TMI-CMS and Technomonk Industries