Benjamin Crozat The web developer life

Print an array in PHP and see what's hidden

Benjamin Crozat Benjamin Crozat1 minute read

Before you start reading this article, did you know 76 persons subscribed to my newsletter?

Join them and enjoy free content about the art of crafting websites!

Print an array in PHP and see what's hidden
Table of contents

There are multiple ways to print the content of an array in PHP.

This article will review each of them built into the language.

print_r() displays arrays in an human-readable format.

Example:

print_r(['Foo', 'Bar', 'Baz']);

Output:

Array
(
[0] => Foo
[1] => Bar
[2] => Baz
)

If you need to capture the output, you can pass a second parameter to print_r():

$output = print_r(['Foo', 'Bar', 'Baz'], true);

var_dump()

var_dump() prints informations about any type of value. It works great for arrays as well!

Example:

var_dump(['Foo', 'Bar', 'Baz']);

Output:

array(3) {
[0]=>
string(3) "Foo"
[1]=>
string(3) "Bar"
[2]=>
string(3) "Baz"
}

You can also print multiple variables at once:

var_dump($foo, $bar, $baz,);

var_export()

var_export() prints a parsable string representation of a variable. It means you could just copy and paste it into your source code.

Example:

$array = ['Foo', 'Bar', 'Baz'];
 
var_export($array);

Output:

array (
0 => 'Foo',
1 => 'Bar',
2 => 'Baz',
)

json_encode()

json_encode() prints can print arrays as JSON.

Example:

$array = ['Foo', 'Bar', 'Baz'];
 
echo json_encode($array);

Output:

["Foo","Bar","Baz"]

Other posts to read

PHP 8.3 will be released in November 2023, and as usual, you need to be up to date with new features and breaking changes for easier transitions.

Redirects in PHP are simple. I will guide you step by step and show you how to dodge some traps. Finally, we'll learn the nuance between 301 and 302 redirects.

Hiring a good developer can be challenging. But if you follow these tips and you will be able to hire the right fit for your projects.

Choose your web hosting provider and deploy your next Laravel project quickly and without any DevOps cost.

Learn why the "Using $this when not in object context" error happens, and let me show you the only way to fix.

AI is a trending topic in the programming space. It enables developers to do incredible things, and many startups build products around it.

Take your code to the next level, thanks to exceptions. Handle errors in a more graceful way within try and catch blocks.

Learn why the "Invalid argument supplied for foreach()" warning happens, and let me show you multiple ways to fix it.

Here are the best GDPR-compliant Google Analytics alternatives to help you avoid the GDPR penalty and keep your users safe.

You heard about Laravel but don't know where to start? Don't worry, you found the best starting point for your journey.