I have really simple problem in my PHP script. There is a function defined which takes variable length argument list:
function foo() {
// func_get_args() and similar stuff here
}
When I call it like this, it works just fine:
foo("hello", "world");
However, I have my variables in the array and I need to pass them "separately" as single arguments to the function. For example:
$my_args = array("hello", "world");
foo(do_some_stuff($my_args));
Is there any do_some_stuff function which splits the arguments for me so I can pass them to the function?
Use
ReflectionFunction::invokeArgs(array $args)
or
call_user_func_array( callback $callback, array $param_arr)
Well you need call_user_func_array
call_user_func_array('foo', $my_args);
http://php.net/manual/en/function.call-user-func-array.php
You are searching for call_user_func_array().
http://it2.php.net/manual/en/function.call-user-func-array.php
Usage:
$my_args = array("hello", "world");
call_user_func_array('foo', $my_args);
// Equivalent to:
foo("hello", "world");
Sounds to me like you are looking for call_user_func_array.
http://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
Isn't this what you want?
edit
ah... ok... how about this:
Passing an Array as Arguments, not an Array, in PHP
If you can change the code of foo() it should be easy to solve this in just one place.
function foo()
{
$args = func_get_args();
if(count($args) == 1 && is_array($args[0]))
{
$args = $args[0]
}
// use $args as normal
}
This solution is not recommended at all, but just showing a possibility :
Using eval
eval ( "foo('" . implode("', '", $args_array) . "' )" );
I know it's an old question but it still comes up as the first search result - so here is an easier way;
<?php
function add(... $numbers) {
$result=0;
foreach($numbers as $number){
$result+=intval($number);
}
return $result;
}
echo add(...[1, 2])."\n";
$a = [1, 2];
echo add(...$a);
?>
Source:
https://www.php.net/manual/en/functions.arguments.php#example-142
Related
I have the following code:
$a=array(15,12,13,25,27,36,18);
$b=array(1,1,1,1,1,1,1);//is it possible to pass only one value=1, instead of array containing seven 1's
// expectation: $b = array(1); or $b= 1;
//instead of $b=array(1,1,1,1,1,1,1);
function array_add($p,$q){
return($p+$q);
}
$c=array_map("array_add",$a,$b);
I want something like:
$a=array(15,12,13,25,27,36,18);
$b=array(1);
function array_add($p,$q){
return($p+$q);
}
$c=array_map("array_add",$a,$b);
Any better solution thanks.
You can use array_map as this, and pass the $param2 with use()
array_map(function($v) use($param2){
//do something
}, $input);
Have a look at array_walk
From Your example, it would be:
function array_add( &$item, $key, $toAdd) {
$item+=$toAdd;
}
array_walk($a, 'array_add', 1);
I would also recommend that you have a look at the answer provided using closure(use)
I am having situation where i want to pass variables in php function.
The number of arguments are indefinite. I have to pass in the function without using the array.
Just like normal approach. Comma Separated.
like test(argum1,argum2,argum3.....,..,,.,.,.....);
How i will call the function? Suppose i have an array array(1,2,3,4,5) containing 5 parameters. i want to call the function like func(1,2,3,4,5) . But the question is that, How i will run the loop of arguments , When calling the function. I tried func(implode(',',array)); But it is taking all return string as a one parameters
In the definition, I also want the same format.
I can pass variable number of arguments via array but i have to pass comma separated.
I have to pass comma separated. But at the time of passing i don't know the number of arguments , They are in array.
At the calling side, use call_user_func_array.
Inside the function, use func_get_args.
Since this way you're just turning an array into arguments into an array, I doubt the wisdom of this though. Either function is fine if you have an unknown number of parameters either when calling or receiving. If it's dynamic on both ends, why not just pass the array directly?!
you can use :
$function_args = func_get_args();
inside your test() function definition .
You can just define your function as
function test ()
then use the func_get_args function in php.
Then you can deal with the arguments as an array.
Example
function reverseConcat(){
return implode (" ", array_reverse(func_get_args()));
}
echo reverseConcat("World", "Hello"); // echos Hello World
If you truely want to deal with them as though they where named parameters you could do something like this.
function getDistance(){
$params = array("x1", "y1", "x2", "y2");
$args = func_get_args();
// trim excess params
if (count($args) > count($params) {
$args = array_slice(0, count($params));
} elseif (count($args) < count($params)){
// define missing parameters as empty string
$args = array_pad($args, count($params), "");
}
extract (array_combine($params, $args));
return sqrt(pow(abs($x1-$x2),2) + pow(abs($y1-$y2),2));
}
use this function:
function test() {
$args = func_get_args();
foreach ($args as $arg) {
echo "Arg: $arg\n";
}
}
I'm not sure what you mean by "same format." Do you mean same type, like they all have to be a string? Or do you mean they need to all have to meet some criteria, like if it's a list of phone numbers they need to be (ddd) ddd-dddd?
If it's the latter, you'll have just as much trouble with pre-defined arguments, so I'll assume you mean you want them all to be the same type.
So, going off of the already suggested solution of using func_get_args(), I would also apply array_filter() to ensure the type:
function set_names() {
function string_only($arg) {
return(is_string($arg));
}
$names_provided = func_get_args();
// Now you have an array of the args provided
$names_provided_clean = array_filter($names_provided, "string_only");
// This pulls out any non-string args
$names = array_values($names_provided_clean);
// Because array_filter doesn't reindex, this will reset numbering for array.
foreach($names as $name) {
echo $name;
echo PHP_EOL;
}
}
set_names("Joe", "Bill", 45, array(1,2,3), "Jane");
Notice that I don't do any deeper sanity-checks, so there could be issues if no values are passed in, etc.
You can use array also using explode http://www.php.net/manual/en/function.explode.php.
$separator = ",";
$prepareArray = explode ( $separator , '$argum1,$argum2,$argum3');
but be careful, $argum1,$argum2, etc should not contain , in value. You can overcome this by adding any separator. $separator = "VeryUniqueSeparator";
I don't have code so can't tell exact code. But manipulating this will work as your requirements.
Here's my problem, I'd like to have a string that would define my function parameters like this :
function blabla($param1, $param2){
my cool code . $param1 . $param2;
}
$params = 'param1, param2';
blabla($params);
The problem is that when I do this, he uses the string 'param1, param2' as ONE arguments instead of TWO like i'd want 2
That's a very backwards thing to want to do, but you'd probably do it by exploding your string into an array of values, and using call_user_func_array to pass those values as the parameters to the function.
function blah($x, $y) {
echo "x: $x, y: $x";
}
$xy = "4, 5";
$params = explode(", ", $xy);
# Just like calling blah("4", "5");
call_user_func_array('blah', $params);
I'll warn you again however that you've probably chosen the wrong solution to whatever your problem is.
How you are wanting to do it, you can't. However, look in to call_user_func_array as it may solve what you are trying to do. Demonstration follows:
function blabla($param1, $param2){
echo "my cool code $param1 $param2";
}
$params = 'does,work';
call_user_func_array('blabla', explode(',', $params));
use explode() php function
function blabla($param){
$params = explode(',', $param);
$param1 = $params[0];
$param2 = $params[1];
}
$params = 'param1, param2';
blabla($params);
PHP is interpreting this as one argument because you have specified a single string, which just happens to include a comma; just something to bear in mind for the future.
Something very simple is:
function blabla($param1, $param2){
my_cool_code . $param1 . $param2;
}
blabla($param1, $param2);
First, a function name must not have a '$'. Secondly, you have only 2 params, you can pass both params through the function, like above.
The code is now good to use :)
In short, I have a function like the following:
function plus($x, $y){
echo $x+$y;
}
I want to tell the function its parameters as array like the following:
$parms = array(20,10);
plus($parms);
But unfortunately, not work.
I'm tired by using another way as the following:
$parms = array(20,10);
$func_params = implode(',', $parms);
plus($func_params);
And also not work, and gives me Error message:
Warning: Missing argument 2 for plus(), called in.....
And now, I'm at a puzzled.
What can I do to work ?
There is a couple things you can do.
Firstly, to maintain your function definition you can use call_user_func_array(). I think this is ugly.
call_user_func_array('plus', $parms);
You can make your function more robust by taking a variable number of params:
function plus(){
$args = func_get_args();
return $args[0] + $args[1];
}
You can simply accept an array and add everything up:
function plus($args){
return $args[0] + $args[1];
}
Or you could sum up all arguments:
function plus($args){
return array_sum($args);
}
This is PHP, there are 10 ways to do everything.
You need to adapt your function so that it only accepts one parameter and then in the function itself, you can process that parameter:
Very simple example:
function plus($arr){
echo $arr[0]+$arr[1];
}
$parms = array(20,10);
plus($parms);
You can easily adapt that to loop through all elements, check the input, etc.
Heh? The error message is very clear: you ask for two parameters in your function, but you only provide one.
If you want to pass an array, it would be a single variable.
function plus($array){
echo ($array[0]+$array[1]);
}
$test = array(1,5);
plus($test); //echoes 6
Use this:
function plus($arr){
$c = $arr[0]+$arr[1];
echo $c;
}
And the you can invoke:
$parms = array(20,10);
plus($parms);
How would I go about writing a function in php with an unknown number of parameters, for example
function echoData (parameter1, parameter2,) {
//do something
}
But when you call the function you can use:
echoData('hello', 'hello2', 'hello3', 'hello'4);
So that more parameters can be sent as the number of parameters will be unknown.
Just for those who found this thread on Google.
In PHP 5.6 and above you can use ... to specify the unknown number of parameters:
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4); // 10
$numbers is an array of arguments.
func_get_args()
function echoData(){
$args = func_get_args();
}
Be aware that while you can do it, you shouldn't define any arguments in the function declaration if you are going to use func_get_args() - simply because it gets very confusing if/when any of the defined arguments are omitted
Similar functions about arguments
func_get_arg()
func_get_args()
func_num_args()
use func_get_args() to retrieve an array of all parameters like that:
$args = func_get_args();
You can then use the array or iterate over it, whatever suits your use-case best.
You can also use an array:
<?php
function example($args = array())
{
if ( isset ( $args["arg1"] ) )
echo "Arg1!";
}
example(array("arg1"=>"val", "arg2"=>"val"));