What are some best practices to ensure compatibility and avoid future problems when using print_r in PHP?

When using print_r in PHP, it is important to ensure compatibility and avoid future problems by properly handling the output. One common issue is that print_r outputs the information directly to the browser, which can cause formatting issues or interfere with other content on the page. To solve this, it is recommended to use the ob_start() and ob_get_clean() functions to capture the output of print_r and then display it in a more controlled manner.

ob_start();
print_r($data);
$output = ob_get_clean();
echo '<pre>' . htmlspecialchars($output) . '</pre>';