• We just launched and are currently in beta. Join us as we build and grow the community.

How to Pretty Print PHP Array

Piticha

Analytics Insight Wizard
P Rep
0
0
0
Rep
0
P Vouches
0
0
0
Vouches
0
Posts
33
Likes
200
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
Creating our PHP Array

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

  1. <?php
  2. //create example array
  3. $array

    =

    array

    (
  4. array

    (
  5. 'id'

    =>

    '1'

    ,
  6. 'firstname'

    =>

    'neovic'

    ,
  7. 'lastname'

    =>

    'devierte'
  8. )

    ,
  9. array

    (
  10. 'id'

    =>

    '2'

    ,
  11. 'firstname'

    =>

    'gemalyn'

    ,
  12. 'lastname'

    =>

    'cepe'
  13. )

    ,
  14. array

    (
  15. 'id'

    =>

    '1'

    ,
  16. 'firstname'

    =>

    'julyn'

    ,
  17. 'lastname'

    =>

    'divinagracia'
  18. )
  19. )

    ;

  20. ?>

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_not_pretty.png

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. echo

    prettyPrint(

    $array

    )

    ;
  6. ?>

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

php_prettify.png

Full Code

Here's the full code.

  1. <?php
  2. //create example array
  3. $array

    =

    array

    (
  4. array

    (
  5. 'id'

    =>

    '1'

    ,
  6. 'firstname'

    =>

    'neovic'

    ,
  7. 'lastname'

    =>

    'devierte'
  8. )

    ,
  9. array

    (
  10. 'id'

    =>

    '2'

    ,
  11. 'firstname'

    =>

    'gemalyn'

    ,
  12. 'lastname'

    =>

    'cepe'
  13. )

    ,
  14. array

    (
  15. 'id'

    =>

    '1'

    ,
  16. 'firstname'

    =>

    'julyn'

    ,
  17. 'lastname'

    =>

    'divinagracia'
  18. )
  19. )

    ;

  20. //creating prettify function
  21. function

    prettyPrint(

    $array

    )

    {
  22. echo

    '<pre>'

    .

    print_r

    (

    $array

    ,

    true

    )

    .

    '</pre>'

    ;
  23. }

  24. //displaying pretty array
  25. echo

    prettyPrint(

    $array

    )

    ;

  26. ?>

That ends this tutorial. Happy Coding :)

 

452,292

323,341

323,350

Top