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>”;
}
Farhamdani

Sharing insights on tech, blogging, and passive income. Follow for more at farhamdani.eu.org!

Drop your comments, but make sure they’re related to the discussion!

I'd be grateful if you could read the Commenting Rules on this blog before posting a comment.

Post a Comment (0)
Previous Post Next Post