How to Print an Array in PHP

Updated onbyAlan Morel
How to Print an Array in PHP

When you're working with arrays in PHP, one of the most common things you'll need to do is print them out to the screen.

This is useful for when you are trying to debug your code or simply to check the value of the elements in the array.

In this post, we'll learn the best ways to print out an array in PHP.

Using a foreach loop

The most straightforward way to print out an array is to use a foreach loop.

This involves simply iterating over the array and using echo to print it out.

Let's look at an example of how this might look in PHP.

$fruits = ['apple', 'banana', 'orange'];

foreach ($fruits as $fruit) {
    echo $fruit . " ";
}
apple banana orange

This method is useful for when you also want to manipulate or use each individual element in the array for another purpose.

Using print_r()

Alternatively, we can use the built-in print_r function to print out the array.

The useful thing about this method is that it also prints out the key of the array.

Let's look at printing out our previous array using print_r.

$fruits = ['apple', 'banana', 'orange'];

print_r($fruits);
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

As you can tell, all you need to do to use this method is to call the function and pass in the array.

Using var_dump()

Finally, we can also use the built-in var_dump function to print out the array.

This function is not specific to arrays as it also dumps any other type of variable.

Either way, it provides another easy-to-use function where all you need to do is pass in the variable you want to print out.

$fruits = ['apple', 'banana', 'orange'];

var_dump($fruits);
array(3) { 
    [0]=> string(5) "apple" 
    [1]=> string(6) "banana" 
    [2]=> string(6) "orange" 
}

This function also has the added benefit of printing out the type of the variable, so you know what you're working with.

Conclusion

In this post, we looked at the different ways to print out an array in PHP.

Your options are to use a foreach loop, print_r, or var_dump, with each option having their own advantages and disadvantages.

Hopefully, this has been useful to you. Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.