spraff
spraff

Reputation: 33445

Why does PHP give undefined index yet still return data for that index?

I have this in a logging function

$e = new Exception ();

$stack = $e -> getTrace ();
$exclude = 'foo.php';

while (isset ($stack [0])
  && ($exclude === substr ($stack [0] ['file'], -strlen($exclude))
      || 'error_handler' === $stack [0] ['function']))
{
    array_shift ($stack);
}

Sometimes this gives

Undefined index: file in bar.php on line 84

What's weird is that if I print out the contents of $stack[0] at any point then there is a file index within that array.

I can avoid this error by adding

isset ($stack [0] ['file'])

in the while condition, but it is logically redundant -- file is always present in $stack[0], I have verified this manually. Furthermore, if I print $stack[0]['file'] within the loop (after the shift) then it can emit an Undefined index warning and still print the data for that index.

How can this be happening?

Upvotes: 0

Views: 68

Answers (1)

bishop
bishop

Reputation: 39434

Unfortunately, 'file' is not always present:

function foo() {
  var_dump((new \Exception)->getTrace()[0]);
}
call_user_func('foo', []);

Outputs:

array(2) {
  ["function"]=>
  string(3) "foo"
  ["args"]=>
  array(1) {
    [0]=>
    &array(0) {
    }
  }
}

There is an ancient bug report on this, but it will not be fixed. If you're using 'file', then guard for 'file', because if the trace flows through a call_user_func (or friends) you won't have it.

Upvotes: 1

Related Questions