Pass undefined index into PHP function

1.2k views Asked by At

I have a function that looks somewhat like this:

function name( param1 = default, param2 = default, param3 = default) {...}

I'm calling the function by passing elements of an array as the parameters like this:

name( $param['foo'], $param['bar'], $param['hello'] );

My question is -- if one (or more) of the elements passed in the function call is undefined, how is it handled within the function itself? I ask because I am trying to call the function but I have no way of knowing if any of the elements are defined.

Inside of the function, I tried debugging a parameter passed through using isset(), is_null(), and empty() and I got false, true, and true respectively. This leads me to believe that since something is actually being passed in, the default value is not set. If anyone could explain how something like this is handled I would appreciate it.

3

There are 3 answers

0
Marc B On BEST ANSWER

The function generally has no clue, and generally doesn't care, WHERE an argument came from. e.g.

$x = 2;
foo($x);
foo(2);

As far as foo() is concerned, it'll just see 2 come in, and nothing will tell it "this 2 was hardcoded" or "this 2 was passed in via a variable".

If you pass in an undefined variable, then the function itself will see a null value arrive, and PHP will spit out a warning about using the undefined variable, BEFORE the function code ever has a chance to start executing.

0
schellingerht On

Calling an undefined index in an array results in a warning.

Two rules for you:

  • Pass/use only defined things
  • Never disable warnings/errors

Example:

$params = ['foo' => 1, 'bar' => null, 'nextKey' => null];

A common approach is to pass the (sub)array:

myMethod($params);

Your method takes the elements it need.

0
user1958756 On

The short answer is that it is passing, NULL which is a constant value designated to represent a null or uninitialized value.