I want to convert all parameters to empty string when NULL is passed. Something like this, but the original value of the parameters is not changed in my code.
function loopThroughArgs($a, $b) {
$args = func_get_args();
foreach ($args as &$arg) {
$arg = $arg === null ? "" : $arg;
}
var_dump($a); // should output an empty string
var_dump($b); // should output an empty string
}
$a = null;
$b = null;
loopThroughArgs($a, $b);
CodePudding user response:
Since func_get_args()
returns a copy of those arguments, it won't automatically change your function parameter variables.
You can use get_defined_vars()
to reassign values. Loop over all declared variables and assign values to each of them from your $args
. If the variable name would have been something different apart from args
, that name will come in your if
condition.
<?php
function loopThroughArgs($a, $b) {
$vars = get_defined_vars();
$args = func_get_args();
foreach ($args as &$arg) {
$arg = $arg === null ? "" : $arg;
}
$ptr = 0;
foreach($vars as $key => $val){
${$key} = $args[$ptr ];
}
var_dump($a); // should output an empty string
var_dump($b); // should output an empty string
}
$a = null;
$b = null;
loopThroughArgs($a, $b);