Page 1 of 1
Passing variable number of arguments from array
Posted: Wed Jan 16, 2008 8:11 pm
by philentropist
Given an array, is it possible to pass its elements as arguments to a function (such as sprintf()) that takes a variable number of arguments?
Re: Passing variable number of arguments from array
Posted: Wed Jan 16, 2008 8:27 pm
by s.dot
Yes.
func_get_args() and
func_num_args() may be useful for you.
EDIT| You'd have to make your own custom function for this. If you simply want to apply a function to every member of an array, use
array_map().
Re: Passing variable number of arguments from array
Posted: Wed Jan 16, 2008 8:31 pm
by jimthunderbird
Sure, you can pass the reference of the array to a function. This is a basic programming fact.
Re: Passing variable number of arguments from array
Posted: Wed Jan 16, 2008 9:11 pm
by philentropist
Let me be more specific about what I need.
The sprintf function takes a variable number of arguments as follows:
sprintf("%d %s cats", 3, "crazy");
The above code outputs "3 crazy cats".
I want to define a function with a variable number of arguments (or one that takes an array), do some processing on the array elements, and pass them to sprintf. The question is how to pass them to sprintf. A reference to the array does not work (sorry Jim, but when you're being condescending you should at least be correct, that's a basic life fact).
For example, can you define a function of an array printPlusOne() that behaves as follows (using sprintf internally)?
printPlusOne("%d", 5); // outputs "6"
printPlusOne("%d %d %d", 1, 2, 3); // ouptuts "2 3 4"
Re: Passing variable number of arguments from array
Posted: Wed Jan 16, 2008 9:17 pm
by Zoxive
From my understanding of the OP, I believe they mean call a function with the Array of Arguments.
Example.
Code: Select all
$Array = array('Hello %s, It is %s','Name', date('m-d-Y'));
echo call_user_func_array('sprintf',$Array);
// Outputs
// Hello Name, It is 01-16-2008
function my_sprintf(array $Data){
return call_user_func_array('sprintf',$Data);
}
echo my_sprintf($Array);
// Outputs
// Hello Name, It is 01-16-2008
Re: Passing variable number of arguments from array
Posted: Wed Jan 16, 2008 9:25 pm
by philentropist
Exactly what I needed. Thanks Zoxive!
Re: Passing variable number of arguments from array
Posted: Thu Jan 17, 2008 12:51 am
by jimthunderbird
+1 for zoxive
