How do I properly use print_r or var_dump?
Asked Answered
J

4

8

I use the following snippet quite often when I am debugging:

echo "<pre>" . var_dump($var) . "</pre>";

And I find I usually get a nice readable output. But sometimes I just don't. I'm particularly vexed at the moment by this example:

<?php

$username='xxxxxx';
$password='xxxxxx';

$data_url='http://docs.tms.tribune.com/tech/tmsdatadirect/schedulesdirect/tvDataDelivery.wsdl';
$start=gmdate("Y-m-d\TH:i:s\Z",time());
$stop =gmdate("Y-m-d\TH:i:s\Z",time()+3600*24);

$client = new SoapClient($data_url, array('exceptions' => 0,
                                          'user_agent' => "php/".$_SERVER[SCRIPT_NAME],
                                          'login'      => strtolower($username),
                                          'password'   => $password));
$data = $client->download($start,$stop);

print_r($data);

?>

I don't want to reveal my credentials of course, but I am told print_r in this case will do the same as my usual snippet when in fact neither print_r nor my snippet produce anything other than runon data with no formatting at all. How can I make it pretty?!

Julenejulep answered 7/2, 2013 at 4:5 Comment(1)
echo "<pre>";print_r($data);Pathos
S
16

var_dump always shows you an array in formatted data, but too much extra stuff

var_dump($data);

But if you want formatted data, here you need to use <pre> tags:

echo '<pre>';
print_r($data);
echo '</pre>';
Spasm answered 7/2, 2013 at 4:20 Comment(0)
P
4

var_dump() echos output directly, so if you want to capture it to a variable to provide your own formatting, you must use output buffers:

   ob_start();
   var_dump($var);
   $s = ob_get_clean();

Once this is done the variable $s now contains the output of var_dump(), so we can safely use:

   echo "<pre>" . $s . "</pre>";
Pandit answered 7/2, 2013 at 4:49 Comment(1)
print_r() acts similarly, but if you set the second parameter as 'true' then can capture its output without use of buffering functions.Pandit
G
3

var_dump is used when you want more detail about any variable.

<?php 
    $temp = "hello" ;
    echo var_dump($temp);
?>

It outputs as follows. string(5) "hello" means it prints the data type of the variable and the length of the string and what is the content in the variable.

While print_r($expression) is used for printing the data like an array or any other object data type which can not directly printed by the echo statement.

Gabbey answered 7/5, 2014 at 8:32 Comment(0)
C
2

Well, print_r() is used to print an array, but in order to display the array in a pretty way you also need HTML tags.

Just do the following:

echo "<pre>";
print_r($data);
echo "</pre>";
Comfort answered 7/2, 2013 at 4:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.