Debugging
Enabling Error Display
Section titled “Enabling Error Display”By default, PHP may hide errors. Enable them during development:
<?phperror_reporting(E_ALL); // Report all errorsini_set('display_errors', 1); // Show errors on screenPlace this at the top of your script or in a config file.
var_dump()
Section titled “var_dump()”Shows the type and value of a variable. Best for debugging.
$name = "John";$age = 25;$prices = [10, 20, 30];
var_dump($name);// string(4) "John"
var_dump($age);// int(25)
var_dump($prices);// array(3) { [0]=> int(10) [1]=> int(20) [2]=> int(30) }print_r()
Section titled “print_r()”Displays arrays and objects in a human-readable format. Easier to read than var_dump() but shows less detail.
$user = [ 'name' => 'John', 'email' => 'john@example.com', 'roles' => ['admin', 'editor']];
print_r($user);// Array// (// [name] => John// [email] => john@example.com// [roles] => Array// (// [0] => admin// [1] => editor// )// )Wrap in <pre> for Better Formatting
Section titled “Wrap in <pre> for Better Formatting”echo '<pre>';print_r($user);echo '</pre>';Quick Debugging Pattern
Section titled “Quick Debugging Pattern”A common pattern for quick debugging:
echo '<pre>';var_dump($variable);echo '</pre>';die(); // Stop execution hereOr as a one-liner:
die(var_dump($variable));Error Reporting Levels
Section titled “Error Reporting Levels”| Constant | Description |
|---|---|
E_ALL | All errors and warnings |
E_ERROR | Fatal runtime errors |
E_WARNING | Runtime warnings |
E_NOTICE | Runtime notices |
// Show all errors except noticeserror_reporting(E_ALL & ~E_NOTICE);
// Show only errors and warningserror_reporting(E_ERROR | E_WARNING);- Always disable error display in production use logging instead
- Use
var_dump()overechofor debugging, it shows the type - Check your PHP error log for errors that don’t display on screen
- Use
exitordie()to stop execution at a specific point