PHP Debugging Techniques
In this page:
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
$data = ["id" => 1, "active" => true];
var_dump($data);
print_r($data);
?>
Login to try C/C++/Java/PHP code in the editor
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
function a() { b(); }
function b() { print_r(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)); }
a();
?>
Login to try C/C++/Java/PHP code in the editor
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
define('DEBUG_MODE', true);
if (DEBUG_MODE) {
echo "Debug: variable value is 42";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$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";
?>
Login to try C/C++/Java/PHP code in the editor
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
$config = ["theme" => "dark", "retries" => 3];
echo var_export($config, true);
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: