Skip to content
PHP Logo

How can the content of print_r($object) be output in an associative array or built in a way to maintain the same structure as the print_r() output?

When using print_r() to output the content of an object, the structure of the output is not in a format that can be directly used as an associative array. To convert the print_r() output into an associative array while maintaining the same structure, you can use output buffering to capture the print_r() output and then parse it to build the associative array.

php
// Start output buffering
ob_start();
// Output the content of the object using print_r()
print_r($object);
// Get the output buffer content and store it in a variable
$output = ob_get_clean();

// Parse the output to build the associative array
$pattern = '/\[(.*?)\] => (.*?)(\n|\r\n?)/';
preg_match_all($pattern, $output, $matches);

$assoc_array = array();
for ($i = 0; $i < count($matches[1]); $i++) {
    $key = $matches[1][$i];
    $value = $matches[2][$i];
    $assoc_array[$key] = $value;
}

// Output the associative array
print_r($assoc_array);