← Back to PHP Course | Chapter 13: Error Handling | Lesson 5 of 5

PHP Debugging Techniques

Simple Print Debugging

var_dump() and print_r() are the fastest way to inspect a variable's actual contents -- var_dump() additionally reveals data types and array/object structure, which matters when a bug turns out to be a type mismatch rather than a wrong value.

Example: Simple Print Debugging

php
<?php
$data = ["id" => 1, "active" => true];
var_dump($data);
print_r($data);
?>

The Backtrace Utilities

debug_backtrace() returns the full chain of function calls that led to the current line, which is invaluable when you land inside a deeply nested call and need to understand how execution got there.

Example: The Backtrace Utilities

php
<?php
function a() { b(); }
function b() { print_r(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)); }
a();
?>

Conditional Debugging

Wrapping debug output in a check against a constant like DEBUG_MODE lets you leave diagnostic code in place without it ever running (or leaking information) in production.

Example: Conditional Debugging

php
<?php
define('DEBUG_MODE', true);
if (DEBUG_MODE) {
    echo "Debug: variable value is 42";
}
?>

Tracking Memory and Time

memory_get_usage() and microtime(true) let you measure exactly how much memory a script consumes and how long a section takes to run, turning vague 'this feels slow' complaints into concrete numbers you can optimize against.

Example: Tracking Memory and Time

php
<?php
$start = microtime(true);
$mem = memory_get_usage();
for ($i = 0; $i < 10000; $i++) {}
echo "Time: " . round(microtime(true) - $start, 4) . "s\n";
echo "Memory: " . (memory_get_usage() - $mem) . " bytes";
?>

Safe Variable Inspection

var_export() produces a string of valid PHP code representing a variable's value, which is handy for generating cache files or config arrays, not just for eyeballing a value during debugging.

Example: Safe Variable Inspection

php
<?php
$config = ["theme" => "dark", "retries" => 3];
echo var_export($config, true);
?>
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.