Skip to main content

Ways to Echo or Print an Array in PHP

TL;DR: This guide covers five methods to echo or print an array in PHP: using print_r(), var_dump(), var_export(), foreach loop, and implode() function. Each method is explained with code examples and console outputs.

Using var_dump() Function

The var_dump() function dumps information about a variable, including its type and value.

$array = ['Monday', 'Tuesday', 'Wednesday'];
var_dump($array);

Console Output

array(3) { [0]=> string(6) "Monday" [1]=> string(7) "Tuesday" [2]=> string(9) "Wednesday" }

Using var_export() Function

The var_export() function outputs or returns a parsable string representation of a variable.

$array = ['Monday', 'Tuesday', 'Wednesday'];
var_export($array);

Console Output

array ( 0 => 'Monday', 1 => 'Tuesday', 2 => 'Wednesday', )

Using foreach Loop

You can use a foreach loop to iterate through the array and echo each element.

$array = ['Monday', 'Tuesday', 'Wednesday'];
foreach ($array as $key => $value) {
    echo "$key => $value\n";
}

Console Output

0 => Monday 1 => Tuesday 2 => Wednesday

Using implode() Function

The implode() function joins array elements with a string.

$array = ['Monday', 'Tuesday', 'Wednesday'];
echo implode(', ', $array);

Console Output

Monday, Tuesday, Wednesday

Interactive Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!