Apologies for the newbie question but i have a function that takes two parameters one is an array one is a variable function createList($array, $var) {}
. I have another function which calls createList with only one parameter, the $var, doSomething($var);
it does not contain a local copy of the array. How can I just pass in one parameter to a function which expects two in PHP?
function createList (array $args = array()) {
//how do i define the array without iterating through it?
$args += $array;
$args += $var;
}
If you can get your hands on PHP 5.6+, there's a new syntax for variable arguments: the ellipsis keyword.
It simply converts all the arguments to an array.
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
Doc: ... in PHP 5.6+
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] **/
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With