Skip to main content

How to Pretty Print PHP Array


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 :)

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.