php:
more readable print_r

When debugging a script in php, the result of print_r with a large array may be unreadable, for example:
$testArray=array(
	"meses"=>array(
		1=>array("en"=>"january","es"=>"enero",
		2=>array("en"=>"february","es"=>"febrero",
		3=>array("en"=>"march","es"=>"marzo",
		4=>array("en"=>"april","es"=>"abril",
		5=>array("en"=>"mai","es"=>"mayo")
	),
	"colors"=>array(
		"#f00"=>array("en"=>"red","es"=>"rojo"),
		"#0f0"=>array("en"=>"green","es"=>"verde"),
		"#00f"=>array("en"=>"blue","es"=>"azul"),
		"#000"=>array("en"=>"black","es"=>"negro"),
		"#fff"=>array("en"=>"white","es"=>"blanco")
	)
);
By using print_r with this array:
print_r($testArray);
It returns:
Array ( [meses] => Array ( [1] => Array ( [en] => january [es] => enero )
[2] => Array ( [en] => february [es] => febrero ) [3] => Array ( [en] =>
march [es] => marzo ) [4] => Array ( [en] => april [es] => abril ) [5] =>
Array ( [en] => mai [es] => mayo ) ) [colors] => Array ( [#f00] => Array
( [en] => red [es] => rojo ) [#0f0] => Array ( [en] => green [es] => verde )
[#00f] => Array ( [en] => blue [es] => azul ) [#000] => Array ( [en] =>
 black [es] => negro ) [#fff] => Array ( [en] => white [es] => blanco ) ) ) 
Wrapping the result of print_r with a PRE tag, make the code more readable and easier to debug:
print "<pre>";
print_r($testArray);
print "</pre>";
It returns:
Array
(
    [meses] => Array
        (
            [1] => Array
                (
                    [en] => january
                    [es] => enero
                )
            [2] => Array
                (
                    [en] => february
                    [es] => febrero
                )
            [3] => Array
                (
                    [en] => march
                    [es] => marzo
                )
            [4] => Array
                (
                    [en] => april
                    [es] => abril
                )
            [5] => Array
                (
                    [en] => mai
                    [es] => mayo
                )

        )
    [colors] => Array
        (
            [#f00] => Array
                (
                    [en] => red
                    [es] => rojo
                )
            [#0f0] => Array
                (
                    [en] => green
                    [es] => verde
                )
            [#00f] => Array
                (
                    [en] => blue
                    [es] => azul
                )
            [#000] => Array
                (
                    [en] => black
                    [es] => negro
                )
            [#fff] => Array
                (
                    [en] => white
                    [es] => blanco
                )
        )
)
We can also make it a function if you frequently use:
function print_rPre($arr){
 print "<pre>";
 print_r($arr);
 print "</pre>";
}

Leave a Reply

Your email address will not be published. Required fields are marked *