1

Am I doing this correctly? As I understand it, if I define the "return" value as true when I call print_r, it should return a string. I have the following function:

function alert($string) {
    echo '<script>alert("' . $string . '");</script>';
}

And when I pass that function a regular old quote-encapsed string, it works just fine and dandy, but when I feed it this:

alert(print_r($array,true));

Nothing happens and I don't see an error, yet echoing print_r($array,true) works. Thanks for any help you can offer, I'm just trying to understand what's going wrong here even though it is obviously a very minor problem.

J S
  • 3,324
  • 4
  • 20
  • 27

3 Answers3

2

Use

<script>
    alert(<?php echo json_encode(print_r($array, true)); ?>);
</script>

instead. Note the use of json_encode - this is to prevent any ' or other JS-metacharacters from introducing a JS syntax error, e.g.:

<?php
$name = "Miles O'Brien"; // note the '-quote in there
?>

<script>
alert('<?php echo $name ?>');
</script>

would give you:

alert('Miles O'Brien');
      ^-- start of string
              ^--end of string
               ^^^^-- unknown variable/function.
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Right, of course I could do this but it's not the point of the function. The point is just to have a little convenience function to save me a few lines. Anyway though, the real reason I'm posting is to understand the cause of the problem, not just to fix it. – J S Sep 23 '13 at 18:11
1

Your alert function has two problems handaling that input. first, as metioned, your JS is missing qutes. Second, the new lines should be converted to the string '\n'. otherwise your call to the alert function (in the js) will end in another line, which is not correct. for example:

    alert("hello
    world");

is invalid syntax.

so, this alert function will probably work:

    function alert($string) {
        $string=preg_replace('/\n/m','\\n',$string);
        echo '<script>alert("' . $string . '");</script>';
    }
user1691388
  • 138
  • 1
  • 7
  • This works for a string, but will fail for arrays. Example: `alert(array('foo', 'bar'));` – Amal Murali Sep 23 '13 at 18:18
  • Right, I know that of course. Obviously I can always set it to just print if it's a string or drop it in print_r and return a string if it's an array. – J S Sep 23 '13 at 18:26
0

print_r (as well as var_dump) outputs its content to stdout. However, you can control this behaviour with PHP's buffers.

Have a look at What is output buffering?, then http://www.php.net/manual/en/ref.outcontrol.php.

Community
  • 1
  • 1
lilly
  • 661
  • 1
  • 7
  • 17
  • 1
    You can (alternatively) set the second parameter of `print_r` to `true` to have it return the string rather than dumping it to stdout. – SamT Sep 23 '13 at 18:06
  • Thanks. It's much cleaner. Reading the docs thoroughly pays off. – lilly Sep 24 '13 at 08:48