Member-only story

Displaying an Array in PHP and Laravel

I Nyoman Jyotisa
2 min readNov 9, 2024

--

There are several ways to output the contents of an array in PHP, including using print_r(), var_dump(), var_export(), and json_encode(). Let's take a look at each method.

Displaying an Array with print_r()

The print_r() function outputs arrays in a format that’s easy to read for humans.

Example:

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

Output:

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

To capture the output instead of displaying it, use true as the second parameter:

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

Displaying an Array with var_dump()

var_dump() provides detailed information on variables, making it useful for arrays.

Example:

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

Output:

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

You can also pass multiple variables to var_dump() at once:

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

Displaying an Array with var_export()

--

--

No responses yet