Skip to content
← Back to Snippets
Code

Using var_dump() for Detailed Debugging

Captures var_dump() output for a value so type and structure details can be reviewed during development without leaking debug text to normal page output.

Purpose

Captures var_dump() output for a value so type and structure details can be reviewed during development without leaking debug text to normal page output.

Snippet details

ContextDebugLevelPracticalCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Using var_dump() for Detailed Debugging.
 *
 * Purpose:
 * Captures var_dump() output so a developer can inspect value types and nested
 * structure during local troubleshooting.
 *
 * @param mixed $value Value to inspect.
 * @param bool $enabled Whether debug capture is allowed.
 * @return string Captured debug text, or a disabled notice.
 */
function ogSnippetVarDumpDebugging($value, bool $enabled): string {
	if ($enabled === false) {
		return 'Debug output disabled.';
	}

	ob_start();
	var_dump($value);
	$debug_output = ob_get_clean();

	if ($debug_output === false) {
		return 'Debug capture failed.';
	}

	return $debug_output;
}

$debug_payload = array(
	'ship' => 'Rocinante',
	'drive_status' => true,
	'crew_count' => 4,
	'ports' => array('Tycho', 'Ceres')
);

$debug_text = ogSnippetVarDumpDebugging($debug_payload, true);

echo $debug_text;