2

Possible Duplicate:
putting print_r results in variable

I'm throwing an exception and trying to include a variable in the exception, like so:

throw new Exception('Oh no, an exception! ' . $variable);

(Where $variable is an array)

The problem is, this only puts the following in my log file:

On no, an exception! Array

Unfortunately I'm not an expert at PHP, I'm guessing this could mean one of two things:

1) $variable is an empty array

2) $varialbe is an array with data in it, but outputting it as such in an exception does not output all of its contents

Please let me know if 1) is the case here (I hope it isn't though)

However, if 2) is the case, how can I get more information about $variable? Is it possible to do print_r or var_dump inside the exception like follows:

throw new Exception('Oh no, an exception! ' . print_r($variable));

Or will that cause problems?

Community
  • 1
  • 1
Sean
  • 6,389
  • 9
  • 45
  • 69
  • 1
    Read [the `print_r()` docs](http://us3.php.net/manual/en/function.print-r.php) Pass the second param as `true` to return the string – Michael Berkowski Dec 07 '12 at 14:58
  • 1
    `$x = array(); echo $x` will **ALWAYS** output `Array`. You're trying to use an array in string context, and arrays show up as `Array`. – Marc B Dec 07 '12 at 15:06
  • @MarcB thanks for the clarification, this makes a lot more sense to me now (I was confused as I remember echoing arrays and them outputting properly) – Sean Dec 07 '12 at 15:07

3 Answers3

9

Or will that cause problems?

Yes, it will. The print_r will be evaluated before the string is fully constructed, and the output will look something like this, if you try and print out the Exception message:

Array
(
    [x] => 5
    [y] => 65
)
Oh no, an exception! 1

To fix this, you need to make sure you set print_r's $return parameter to true so the value is returned rather than echoed:

throw new Exception('Oh no, an exception! ' . print_r($variable, true));
6

Use a second argument of true to have the output returned instead of instantly outputted.

print_r($variable, true)

Documentation is your friend

Rawkode
  • 21,990
  • 5
  • 38
  • 45
4

If you look at the documentation for print_r, you will see that the second argument, if truthy, causes the function to return the information as a string rather than emit it immediately.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405