• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Return information from PHP print_r instead of displaying it

Return information from PHP print_r instead of displaying it

print_r is a useful PHP function for displaying the values of an array or object when debugging etc. Having been a PHP programmer since the days of PHP 3.x (and not having read the manual page for this function in years) I didn’t realise this function had added the capability to return the information as well as print it from PHP 4.3.0 and only discovered this in the last few days. This post gives a brief overview of PHP’s print_r function.

Let’s say for example you have the following array:

$myarray = array(
  "wd" => "well done",
  "m" => "medium",
  "mr" => "medium rare",
  "r" => "rare"
);

Doing this:

print_r($myarray);

will output this:

Array
(
    [wd] => well done
    [m] => medium
    [mr] => medium rare
    [r] => rare
)

If you want to instead suppress the output and return the array information into a variable (which could be emailed in an error report, for example) set the second optional parameter to print_r to true like so:

$info = print_r($myarray);

The output will now not be displayed and the example output above will instead be stored into the $info variable. This should work for any variable types. The following examples would also store the output from print_r into the $info variable instead of outputting to standard output.

$foo = "bar";
$info = print_r($foo, true);

$info = print_r(some_function_call(), true);

$foo = new some_class();
$info = print_r($foo);

It’s really useful to be able to capture information like this using print_r because it means you can use it to store into error logs or send in an error email, as well as for debugging purposes. I only wish I’d known about the additional parameter when it first became available 🙂

Check Out These Related posts:

  1. Type casting with PHP
  2. Get unique array values with PHP
  3. Intialise an array in PHP with default values
  4. Backtracing with PHP Part 1

Filed Under: PHP

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap