0

HTML form sends empty values as empty strings. I want them to be null:

function dummy($arg1, $arg2, ... $argN)
{
   if(!$arg1) $arg1 = null;
   if(!$arg2) $arg2 = null;
   ... 
   if(!$argN) $argN = null

}

This is very ugly. I want something like:

function dummy($arg1, $arg2, ... $argN)
{
   nullEmptyArguments();
   var_dump($arg1); //null
}
2
  • 3
    Why set the arguments to null? If they are only set to null when they evaluate to false, then simply checking the condition (!$arg1) is equivalent to checking, setting to null, and later checking for null. Commented Oct 8, 2013 at 13:27
  • This is not a problem you typically need a solution for. Sounds like you should structure your code inside your function differently. It really hardly makes sense to do what you are doing. Commented Oct 8, 2013 at 13:41

1 Answer 1

1

Use function get_defined_vars() to get all defined variables, and loop over them and re-set them:

function dummy($arg1, $arg2, $argN)
{
    foreach (get_defined_vars() as $k => $v) $$k = $v ?: null;
    // your logic
}

dummy(1, '0', ''); # $arg2 & $argN will be set to NULL
Sign up to request clarification or add additional context in comments.

4 Comments

good point from the $$, because with $v doesn't work. but what about the &$ ?
@BubuDaba: I don't understand what doesn't work with $v? And what do you mean by &$? What would you like to pass by reference?
Oh I meant if dummy($a,$b,$c), to change the variables
If you would use function dummy(&$arg1, &$arg2, &$argN) then your input must be variables like you shown, and not values, like in my answer, because you would get Fatal error: Only variables can be passed by reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.