PHP: Functions with arbitrary number of arguments

Sometimes you may have to use a function with a variable number of arguments. Here is a simple method of passing a list of variables to a function:


function foo() {

// returns an array of all passed arguments
$args = func_get_args();

foreach ($args as $k => $v) {
echo "arg".($k+1).": $v\n";
}

}

foo();
/* prints nothing */

foo('hello');
/* prints
arg1: hello
*/

foo('hello', 'world', 'again');
/* prints
arg1: hello
arg2: world
arg3: again
*/

For more interesting functions and futures, read the 9 useful php functions and futures you need to know article on net.tutsplus.com.

Bookmark and Share

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s