How do I properly use print_r or var_dump? - php

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?!

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>';

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>";

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.

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>";

Related

I can't change JSON into a PHP array

For some strange reason I can't change the following JSON to a PHP array:
{"sides0":{"name_nl":"Voorkant100","name":"Frontside100","template_overlay":""},"sides1":{"name_nl":"Achterkant100","name":"Backside100","template_overlay":"1"}}
I've validated the json and it's valid.
First I post $product['sides'] to my page, containing:
"{\"sides0\":{\"name_nl\":\"Voorkant100\",\"name\":\"Frontside100\",\"template_overlay\":\"\"},\"sides1\":{\"name_nl\":\"Achterkant100\",\"name\":\"Backside100\",\"template_overlay\":\"1\"}}"
Then I use json_decode on it like this:
$sidearr = json_decode($product['sides'], true);
If I then do:
echo '<pre>';
print_r($sidearr);
echo '</pre>';
It prints the first part of my question.
Now I want to loop over it, but even this test shows nothing:
foreach($sidearr as $side){
echo 'test';
}
I tried testing if it even is an array with:
echo is_array($sidearr) ? 'Array' : 'not an Array';
echo "\n";
And it shows me that it is not an array. Why is that? I always thought using json_decode on a json string and add true inside the function turns it into a PHP array.
It prints the first part of my question.
Because $sidearr is a string now, decode it again, you'll get an array.
$sidearr = json_decode($sidearr, true);

Why is the "1" appended?

In this program
<?php
$bp = array();
echo print_r($bp).'<BR>';
?>
why is there a "1" appended when the echo executes?
Because by default print_r() returns a status 1 = ok 0 = failed
So you should code the print_r() without the echo as its output goes direct to the output stream and the echo is unnecessary.
You also need to echo the <br> seperately.
<?php
$bp = array();
print_r($bp);
echo '<BR>';
?>
By default, print_r() prints the output itself and returns TRUE, which is converted to 1 when it gets echoed.
If you want print_r() to return its result instead of printing, so you can concatenate it, give it a second argument TRUE.
echo print_r($bp, true).'<BR>';
If printing with print_r() is successful print_r() returns true you can use print_r($youVar,true) to have it removed.

How to show an array's contents?

I have a function (this function is from a class) from Github
<?php
function func ($expr, $bindParams = null) {
return Array ("[F]" => Array($expr, $bindParams));
}
$a = func('SHA1(?)', array("MYPASSWORD".'salt123'));
echo $a;
?>
This $a shows as array. I think the above function is for encrypting password. How can I echo this encrypted $a?
To see the contents of array you can use.
1) print_r($a)); or if you want nicely formatted array then
echo '<pre>'; print_r($a)); echo '</pre>';
2) use var_dump($a)) to get more information of the content in the array like datatype and length.
3) you can loop the array using php's foreach(); and get the desired output. more info on foreach in php's documentation website http://in3.php.net/manual/en/control-structures.foreach.php
Array's cannot be echoed. PHP has a perfect debug function to do this called var_dump().
echo "<pre>";
var_dump($a);
echo "</pre>";
exit;
It can also be done using the print_r() function.
Note on var_dump(): It will not dump the complete array most of the times. You can set the depth for var_dump() in your php.ini file.

How do I display print_r on different lines?

When I run the following code:
echo $_POST['zipcode'];
print_r($lookup->query($_POST['zipcode']));
?>
the results are concatenated on one line like so: 10952Array.
How can I get it to display on separate lines, like so:
08701
Array
You might need to add a linebreak:
echo $_POST['zipcode'] . '<br/>';
If you wish to add breaks between print_r() statements:
print_r($latitude);
echo '<br/>';
print_r($longitude);
to break line with print_r:
echo "<pre>";
print_r($lookup->query($_POST['zipcode']));
echo "</pre>";
The element will format it with any pre-existing formatting, so \n will turn into a new line, returned lines (when you press return/enter) will also turn into new lines.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
If this is what your browser displays:
Array ( [locus] => MK611812 [version] => MK611812.1 [id] => 1588040742 )
And this is what you want:
Array
(
[locus] => MK611812
[version] => MK611812.1
[id] => 1588040742
)
the easy solution is to add the the <pre> format to your code that prints the array:
echo "<pre>";
print_r($final);
echo "</pre>";
Old question, but I generally include the following function with all of my PHP:
The problem occurs because line breaks are not normally shown in HTML output. The trick is to wrap the output inside a pre element:
function printr($data) {
echo sprintf('<pre>%s</pre>',print_r($data,true));
}
print_r(…, true) returns the output without (yet) displaying it. From here it is inserted into the string using the printf function.
Just echo these : echo $_POST['zipcode']."<br/>";

Accessing a variable that starts with an integer within results generated by json_decode

I feel really stupid right now. The following code should output 'If you can get this text to print, you're neat!', but it doesn't. Any ideas?
<?php
$a = (Array) json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}");
// dump($a);
echo $a[406]."\n";
echo $a["406"]."\n";
echo $a['"406"']."\n";
echo $a["'406'"]."\n";
$a = Array(406=>'Sanity check: this works, why don\'t any of the previous accessors work?');
// dump($a);
echo $a[406]."\n";
function dump($a) {
foreach ($a as $k => $v) {
echo "$k=>$v\n";
}
}
?>
Your original example was returning an object because of a second optional parameter for return type that has the default of FALSE, or to return an object. This is how you would treat it...
$a = json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}", FALSE);
echo $a->{"406"}; // If you can get this text to print, you're neat!
A little tweaking and you can create an array instead...
$a = json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}", TRUE);
echo $a["406"]; // If you can get this text to print, you're neat!
... and you can reference $a as an array like you were originally attempting. Notice what was happening when you were trying to type cast the original object. Here's a var_dump of the original array you created followed by the resulting array from using the optional TRUE parameter.
array(1) { ["406"]=> string(47) "If you can get this text to print, you're neat!" }
array(1) { [406]=> string(47) "If you can get this text to print, you're neat!" }
Do you see how it was adding the quotes to your array key when you were type casting it from an object? This is why you weren't able to return the correct value; because the array key had changed.
This did work for me:
$a = json_decode("{\"406\":\"If you can get this text to print, you're neat!\"}", true);
I added another parameter to json_deocde.
Your using a json object, not an array.
json object:
{"keyname":"keyvalue"}
Json array:
["value1","value2"]
Since it is an object, you can access it as such.
$json=json_decode("{'keyname':'keyvalue'}";
$keyname=$json->keyname;

Categories