3

I always find myself writing something like:

if(isset($var))
{
    DoSomethingWith($var);
}
else
{
    DoSomethingWith(null);
}

or

if(isset($arr["key"]))
{
    DoSomethingWith($arr["key"];
}
else
{
    DoSomethingWith(null);
}

My question is exacly this:

Is there a way to write a get_var_if_set() function so that you can simply write...

DoSomethingWith(get_var_if_set($var));
/// and
DoSomethingWith(get_var_if_set($arr["key"]));

....WITHOUT notifying if $var doesn't exists or that $arr doesn't have a set value for "key"?

I guess it should be something like this:

function get_var_if_set($a)
{
    return (isset($a) ? $a : null);
}

But that doesn't work because calling get_var_if_set() with unset variables will always generate a Notice, so it might need a little magic.

Thanks all folks.

Edit A user who deleted his answer suggested to pass variables by reference, as PHP will pass null if the $variable doesn't exist.

So that would be perfect, take a look at these solutions (which might probably be equivalent):

function get_var_if_set(&$a) { return (isset($a) ? $a : null); }
function get_var_if_set(&$a) { return $a ?? null; } // Only in PHP 7.0+ (Coalescing operator)

Note: Coalescing operator suggested by Koray Küpe

The problem as you can see is that they initialize the passed variables somehow in the return statement. We don't want that.

Community
  • 1
  • 1
J. Brown
  • 124
  • 7

2 Answers2

4

If you use PHP 7.0+ you can use null coalescing operator.

return $a ?? null;

Note: The operator checkes whether the variable exist and not empty. So, if the variable is already set but empty, it will return the null variable already.

Koray Küpe
  • 716
  • 6
  • 24
  • That's smart, but [it does spit out notifications](https://eval.in/789705)! The problem is when you execute _call_a_function_with($some_unexistent_parameter);_ PHP gets angry. I want a "magic function" that tells PHP "It doesn't matter what I'm passed, nor if it exists or not, I'm built to handle undefined indexesand unknown variables." – J. Brown May 08 '17 at 13:14
0

The problem is not the var itself, but the key of the array key in this:

DoSomethingWith(get_var_if_set($arr["key"]))

So the only solution is to check for the array and the key you're looking for.

function get_var_if_set($a, $key = null)
{
    if(is_array($a) && array_key_exists($key, $array)) {
        return $a[$key]; 
    } else {
          return (isset($a) ? $a : null);
    }
}
napolux
  • 15,574
  • 9
  • 51
  • 70
  • The coolness of the function isset() is that you can give it things that don't exist, and at most you will get false; PHP knows isset() might receive inexistent variables and it doesn't notify it. I want sort of wrapper-function for isset, that gives you directly [value or null], not [true or false]. Your solution ignores the problem that if you call get_var_if_set($inexistent_var), PHP tells you (with a notice) that $inexistent_var doesn't exist. – J. Brown May 08 '17 at 13:47