PHP - Outputting an Entire Array with print_r()

Introduction

Use PHP print_r() to output the contents of an array for debugging.

Using print_r() is easy - just pass it the array you want to output:

print_r($array);

The following example code creates an indexed array and an associative array, then displays both arrays in a Web page using print_r().

Demo

<?php

         $authors = array("A","B","C","D");

         $myBook = array("title" => "Java",
                         "author" => "John A",
                         "pubYear" =>  2018);

         print_r ($authors);//w  w w .  ja va 2  s  .com
         print_r ($myBook);

?>

Result

To store the output of print_r() in a string, rather than displaying it in a browser, pass a second true argument to the function:

Demo

<?php

         $arrayStructure = print_r($array, true);
         echo $arrayStructure;  // Displays the contents of $array
?>//w  w w. j  av  a  2  s  .  com

Result

Related Topic