How to: Print php array as php code format

Today i will give you a function to print php array as php code format.

To print, you can use this function:

PHP4:

function print_array($arr){

echo “<pre><ul style=’list-style: none’><li style=’list-style: none’>array(“; print_r(get_print_array($arr)); echo “);</li></ul></pre>”;

}

function get_print_array($arr){

$str = ‘<ul style=”list-style: none”>’;

if (is_array($arr)){

foreach ($arr as $key=>$val){

$key = is_numeric($key) ? $key : “‘{$key}’”;

if (is_array($val)){

$str .= “<li style=’list-style: none’>{$key} => array(“.get_print_array($val).”),</li>”;

}else{

$val = is_numeric($val) ? $val : “‘{$val}’”;

$str .= “<li style=’list-style: none’>{$key} => {$val},</li>”;

}

}

}

$str .= ‘</ul>’;

return $str;

}

 

PHP5:

function print_array_php5($arr){

$printFunc = function($arr, $callback) {

$str = ‘<ul style=”list-style: none”>’;

if (is_array($arr)){

foreach ($arr as $key=>$val){

$key = is_numeric($key) ? $key : “‘{$key}’”;

if (is_array($val)){

$val = call_user_func_array($callback, array($val, $callback));

$str .= “<li style=’list-style: none’>{$key} => array({$val}),</li>”;

}else{

$val = is_numeric($val) ? $val : “‘{$val}’”;

$str .= “<li style=’list-style: none’>{$key} => {$val},</li>”;

}

}

}

$str .= ‘</ul>’;

return $str;

};

$str = $printFunc($arr, $printFunc);

echo “<pre><ul style=’list-style: none’><li style=’list-style: none’>array(“; print_r($str); echo “);</li></ul></pre>”;

}