Table of Contents
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.
PHP$fruits = ['apple', 'banana', 'orange'];
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
BASHapple 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
.
PHP$fruits = ['apple', 'banana', 'orange'];
print_r($fruits);
BASHArray
(
[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.
PHP$fruits = ['apple', 'banana', 'orange'];
var_dump($fruits);
BASHarray(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!
- Managing PHP Dependencies with Composer
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase