How to Pass Variable Number of Arguments to a PHP Function

How to pass variable number of arguments to a PHP function

If you have your arguments in an array, you might be interested by the call_user_func_array function.

If the number of arguments you want to pass depends on the length of an array, it probably means you can pack them into an array themselves -- and use that one for the second parameter of call_user_func_array.

Elements of that array you pass will then be received by your function as distinct parameters.



For instance, if you have this function :

function test() {
var_dump(func_num_args());
var_dump(func_get_args());
}

You can pack your parameters into an array, like this :

$params = array(
10,
'glop',
'test',
);

And, then, call the function :

call_user_func_array('test', $params);

This code will the output :

int 3

array
0 => int 10
1 => string 'glop' (length=4)
2 => string 'test' (length=4)

ie, 3 parameters ; exactly like iof the function was called this way :

test(10, 'glop', 'test');

pass variable number of arguments (both key & value) in PHP

You cannot dictate the "names" of arguments from outside a function.

function ($foo, $bar) ...

Here the first positional argument will be assigned to variable $foo, the second one to $bar.

function () {
$args = func_get_args();
...
}

Here all positionally passed arguments will be assigned to an array $args. The values themselves have no "name", because "names" aren't passed.

If you pass an array with key-value pairs, as you do, then your argument is an array which contains key-value pairs. The array itself still plays according to the above rules.

Maybe you're looking for extract(), or maybe what you want is simply not how it works.

Variable number of parameters in PHP

PHP 5.6 introduces ability to have this exact construct.
From PHP manual:

Argument lists may include the ... token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array

<?php
function sum($acc, ...$numbers) {
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}

echo sum(1, 2, 3, 4);
?>

http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

passing multiple arguments to function php

You have a couple of options here.

First is to use optional parameters.

  function myFunction($needThis, $needThisToo, $optional=null) {
/** do something cool **/
}

The other way is just to avoid naming any parameters (this method is not preferred because editors can't hint at anything and there is no documentation in the method signature).

 function myFunction() {
$args = func_get_args();

/** now you can access these as $args[0], $args[1] **/
}

PHP code for a variable number of parameters

As others have said, you are missing the closing parenthesis on each of your if statements. You open two, but only close one.

While Ghost's answer is more elegant, it is also a bit more advanced. Here is a simpler way that might be more clear as to how it works:

function sum_warehouses_stock($warehouses){

$total = 0;
foreach($warehouses as $warehouse){
if (is_numeric($warehouse)){
$total += $warehouse;
}
}
return $total;
}

This one will accept an array of numbers. It will then loop through each of those. If it is numeric, it will add it to the total. The total will then be returned.

To call the function, you need to pass it an array of values such as:

sum_warehouses_stock([5,0,20]);

or possibly based on your situation:

$warehouses = array(qldstocklevel[1], vickstocklevel[1], wastocklevel[1]);
sum_warehouses_stock($warehouses);

There's probably a better way to do this, because this fixes it to only three warehouses every time. It's better to make it more generic by allowing a variable number of warehouses.

Update

If you are unable to create an array of values outside of the function, then you are better off using the func_get_args() function as follows:

function sum_warehouses_stock(){

$total = 0;
$warehouses = func_get_args();

foreach($warehouses as $warehouse){
if (is_numeric($warehouse)){
$total += $warehouse;
}
}
return $total;
}

Then you can call it with a variable amount of warehouses:

sum_warehouses_stock(1, 5, 9);

or

sum_warehouses_stock(qldstocklevel[1], vickstocklevel[1], wastocklevel[1]);

This answer is now very similar to simonw16's answer.

PHP - Pass by reference a variable number of arguments

First thing I want to mention: Don't use references.

That aside: Doing that directly is impossible as the engine has to know whether something is a reference before calling the function. What you can do is passing an array of references:

$a = 1; $b = 2; $c = 3;
$parameters = array(&$a, &$b, &$c, /*...*/);
func($parameters);

function func(array $params) {
$params[0]++;
}

PHP use variable to pass multiple arguments to function

You should try replacing the "func" string with array($this->ModelName, 'functionname'). The first element in this array is the object on which you call the method, the second is a string representation of the name of this method. This way it should work:

$params = explode(',', $str);
call_user_func_array(array($this->ModelName, 'functionname'), $params);

Of course replace the placeholder names with your own.

How to pass a variable number of parameters to a function in PHP

Not sure if this is what you want, as I didn't read all of that, but check out:

call_user_func_array('array_diff', $values)

Maybe that's what you want.

Passing 20+ arguments into a function

I believe the best way to get complex values ​​either through dependency injection, using a more advanced programming model, especially object-oriented

function shortexample(\stdClass $args) {
$body = array(
'username' => $args->username,
'password' => $args->pass,
'campaign_id' => $args->id,
);
}

You should improve the definition of objects that will be received, using interfaces

//....
interface shortExampleInterface {
public function getUsername();
public function getPass();
public function getId();
}



function shortexample(\shortExampleInterface $args) {
$body = array(
'username' => $args->getUsername(),
'password' => $args->getPass(),
'campaign_id' => $args->getId(),
);
}

But I see that as the context may actually require very parameters, it is worth trying the new feature of PHP 5.6:

Variadic Functions

This feature allows you to capture a variable number of arguments to a function, combined with "normal" arguments passed in if you like. It's easiest to see with an example:

function concatenate($transform, ...$strings) {
$string = '';
foreach($strings as $piece) {
$string .= $piece;
}
return($transform($string));
}

echo concatenate("strtoupper", "I'd ", "like ",
4 + 2, " apples");

The parameters list in the function declaration has the ... operator in it, and it basically means " ... and everything else should go into $strings". You can pass 2 or more arguments into this function and the second and subsequent ones will be added to the $strings array, ready to be used.

Example 2:

function f($req, $opt = null, ...$params) {
// $params is an array containing the remaining arguments.
printf('$req: %d; $opt: %d; number of params: %d'."\n",
$req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);


Related Topics



Leave a reply



Submit