PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 5.9 Dumping Variable Contents as Strings

5.9.1 Problem

You want to inspect the values stored in a variable. It may be a complicated nested array or object, so you can't just print it out or loop through it.

5.9.2 Solution

Use print_r( ) or var_dump( ):

$array = array("name" => "frank", 12, array(3, 4));

print_r($array);
Array
(
    [name] => frank
    [0] => 12
    [1] => Array
        (
            [0] => 3
            [1] => 4
        )
)
var_dump($array);
array(3) {
  ["name"]=>
  string(5) "frank"
  [0]=>
  int(12)
  [1]=>
  array(2) {
    [0]=>
    int(3)
    [1]=>
    int(4)
  }
}

5.9.3 Discussion

The output of print_r( ) is more concise and easier to read. The output of var_dump( ), however, gives data types and lengths for each variable.

Since these functions recursively work their way through variables, if you have references within a variable pointing back to the variable itself, you can end up with an infinite loop. Both functions stop themselves from printing variable information forever, though. Once print_r( ) has seen a variable once, it prints *RECURSION* instead of printing information about the variable again and continues iterating through the rest of the information it has to print. When var_dump( ) sees a variable more than three times, it throws a fatal error and ends script execution. Consider the arrays $user_1 and $user_2, which reference each other through their friend elements:

$user_1 = array('name' => 'Max Bialystock',
                'username' => 'max');

$user_2 = array('name' => 'Leo Bloom',
                'username' => 'leo');

// Max and Leo are friends
$user_2['friend'] = &$user_1;
$user_1['friend'] = &$user_2;

// Max and Leo have jobs
$user_1['job'] = 'Swindler';
$user_2['job'] = 'Accountant';

The output of print_r($user_2) is:

Array
(
    [name] => Leo Bloom
    [username] => leo
    [friend] => Array
        (
            [name] => Max Bialystock
            [username] => max
            [friend] => Array
                (
                    [name] => Leo Bloom
                    [username] => leo
                    [friend] => Array
 *RECURSION*
                    [job] => Accountant
                )

            [job] => Swindler
        )

    [job] => Accountant
)

When print_r( ) sees the reference to $user_1 the second time, it prints *RECURSION* instead of descending into the array. It then continues on its way, printing the remaining elements of $user_1 and $user_2.

Confronted with recursion, var_dump( ) behaves differently:

array(4) {
  ["name"]=>
  string(9) "Leo Bloom"
  ["username"]=>
  string(3) "leo"
  ["friend"]=>
  &array(4) {
    ["name"]=>
    string(14) "Max Bialystock"
    ["username"]=>
    string(3) "max"
    ["friend"]=>
    &array(4) {
      ["name"]=>
      string(9) "Leo Bloom"
      ["username"]=>
      string(3) "leo"
      ["friend"]=>
      &array(4) {
        ["name"]=>
        string(14) "Max Bialystock"
        ["username"]=>
        string(3) "max"
        ["friend"]=>
        &array(4) {
          ["name"]=>
          string(9) "Leo Bloom"
          ["username"]=>
          string(3) "leo"
          ["friend"]=>
          &array(4) {
            ["name"]=>
            string(14) "Max Bialystock"
            ["username"]=>
            string(3) "max"
            ["friend"]=>
            &array(4) {
              ["name"]=>
              string(9) "Leo Bloom"
              ["username"]=>
              string(3) "leo"
              ["friend"]=>
              &array(4) {
<br />
<b>Fatal error</b>:  Nesting level too deep - recursive dependency? in 
<b>var-dump.php</b> on line <b>15</b><br />

It's not until the fourth appearance of the reference to $user_1 that var_dump( ) stops recursing. When it does, it throws a fatal error, and no more variable dumping (or script execution) occurs.

Even though print_r( ) and var_dump( ) print their results instead of returning them, you can capture the data without printing it using output buffering:

ob_start();
var_dump($user);
$dump = ob_get_contents();
ob_end_clean();

This puts the results of var_dump($user) in $dump.

5.9.4 See Also

Output buffering is discussed in Recipe 8.13; error handling with PEAR's DB module, shown in Recipe 10.9, uses output buffering with print_r( ) to save error messages; documentation on print_r( ) at http://www.php.net/print-r and var_dump( ) at http://www.php.net/var-dump .

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    Chapter 5. Variables
    5.1 Introduction
    Recipe 5.2 Avoiding==Versus=Confusion
    Recipe 5.3 Establishing a Default Value
    Recipe 5.4 Exchanging Values Without Using Temporary Variables
    Recipe 5.5 Creating a Dynamic Variable Name
    Recipe 5.6 Using Static Variables
    Recipe 5.7 Sharing Variables Between Processes
    Recipe 5.8 Encapsulating Complex Data Types as a String
    Recipe 5.9 Dumping Variable Contents as Strings
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele