Quick Ways to Print PHP 2D Arrays for Debugging

This guide explains five practical techniques—print_r, var_dump, json_encode, nested foreach loops, and var_export—to display or export two‑dimensional PHP arrays in browsers or CLI, including code examples, formatting tips, and handling of HTML special characters.

php Courses
php Courses
php Courses
Quick Ways to Print PHP 2D Arrays for Debugging

Using print_r()

The print_r() function prints an array in a readable, recursive format. Call it with the 2D array variable, optionally wrap the output in <pre> tags for HTML readability, and use htmlspecialchars() to escape special characters.

Example:

print_r($arr);

Using var_dump()

var_dump()

shows each element's value, type, and length, which is useful for detailed inspection.

Typical usage: var_dump($arr); To capture the output as a string, combine ob_start() and ob_get_clean().

Converting to JSON with json_encode()

json_encode()

converts the array to a JSON string, making it easy to read or send to the front end. Use the JSON_PRETTY_PRINT option for formatted output, and apply htmlspecialchars() when embedding in HTML.

Example:

echo json_encode($arr, JSON_PRETTY_PRINT);

Manual output with nested foreach loops

Iterate over the outer array and then each inner array to fully control the output format, such as adding custom HTML tags or delimiters.

foreach ($arr as $key1 => $subArr) {
    foreach ($subArr as $key2 => $val) {
        echo "[$key1][$key2] => $val
";
    }
}

Exporting with var_export()

var_export()

generates valid PHP code representing the array. Pass true as the second argument to return the string instead of printing it, then output with echo or print. Apply htmlspecialchars() for HTML contexts.

Example:

echo var_export($arr, true);
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Debuggingforeachjson_encodeprint_rvar_dumpvar_export
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.