How to Pretty Print PHP Array

Submitted by: 
Language: 
Visitors have accessed this post 573 times.

Creating our PHP Array

First, we are going to create a sample PHP array.

  1. <?php
  2. //create example array
  3. $array = array(
  4. 'id' => '1',
  5. 'firstname' => 'neovic',
  6. 'lastname' => 'devierte'
  7. ),
  8. 'id' => '2',
  9. 'firstname' => 'gemalyn',
  10. 'lastname' => 'cepe'
  11. ),
  12. 'id' => '1',
  13. 'firstname' => 'julyn',
  14. 'lastname' => 'divinagracia'
  15. )
  16. );
  17.  
  18. ?>

Printing the Array

Then, we use print_r() function to view item in our array.

  1. <?php
  2. print_r($array);
  3. ?>

The default display will look something like this:

array display not pretty

Prettifying our Array

Finally, we prettify the display of our array by creating a function.

  1. <?php
  2. function prettyPrint($array) {
  3. echo '<pre>'.print_r($array, true).'</pre>';
  4. }
  5.  
  6. echo prettyPrint($array);
  7. ?>

Adding the above code will prettify the display of our array and it will look something like this.

pretty array display

Full Code

Here's the full code.

  1. <?php
  2. //create example array
  3. $array = array(
  4. 'id' => '1',
  5. 'firstname' => 'neovic',
  6. 'lastname' => 'devierte'
  7. ),
  8. 'id' => '2',
  9. 'firstname' => 'gemalyn',
  10. 'lastname' => 'cepe'
  11. ),
  12. 'id' => '1',
  13. 'firstname' => 'julyn',
  14. 'lastname' => 'divinagracia'
  15. )
  16. );
  17.  
  18. //creating prettify function
  19. function prettyPrint($array) {
  20. echo '<pre>'.print_r($array, true).'</pre>';
  21. }
  22.  
  23. //displaying pretty array
  24. echo prettyPrint($array);
  25.  
  26. ?>

That ends this tutorial. Happy Coding :)


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.