A Better Way to Print Arrays in PHP

While working with arrays in PHP we often verify that the desired data is present in the array in the correct place or not. Printing the array makes it easier to verify. We are all aware of the most traditional way to print and array using the print_r() method, which prints the whole array in a single line and it is difficult to read. Below is an example of printing an array with the print_r() method.

// Let say $array is an array which has multiple data.
print_r($array);

The above code will print the array in one line as shown in the image below.

Instead, we can use the below code to print the array in a prettier format which will be more easy to read.

print("<pre>".print_r($array,true)."</pre>");

The above code will print the array in a pretty format as shown in the image below.

SHARE ON:
Rajesh Patra
Rajesh Patra

I am a passionate Full Stack Engineer with around a decade of experience in Web Application Development. With a background in crafting dynamic web applications, my professional journey led me to establish a digital space where I share knowledge and help others develop their skills.

Leave a Reply

Your email address will not be published. Required fields are marked *