Mads Phillip Mads Phillip - 27 days ago 6
PHP Question

Using array_map to make an alternative to print_r to produce a 'cleaner' output

I need a cleaner output than print_r gives me

an array like

$array = array(1,2,3,"four"=>array(4.1,4.2));


should print out somthing like this

0: 1
1: 2
2: 3
[four]
0: 4.1
1: 4.2


I've come up with this, but the array_map does not return what I expected

function print_array($array) {
$string = "";

foreach ( $array as $key => $value ) {
if (is_array ( $value )) {
$string .= "[" . $key . "]\r\n" . array_map ( 'print_array', $value );
} else {
$string .= $key . ": " . $value . "\r\n";
}
}
return $string;
}


The output from this is

0: 1
1: 2
2: 3
[four]
Array


my array_map use is apparently wrong can anyone enlighten me?

Answer

Use this it may help you , call your function recursively if value is an array.

<?php 

function print_array($array) {
    $string = "";
    foreach ( $array as $key => $value ) {
        if (is_array ( $value )) {
            $string .= "[" . $key . "]\r\n" . print_array($value );
        } else {
            $string .= $key . ": " . $value . "\r\n";
        }
    }
    return $string;
}

$array = array(1,2,3,"four"=>array(4.1,4.2));
print_r(print_array($array));
?>

Output

0: 1
1: 2
2: 3
[four]
0: 4.1
1: 4.2