3

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?

2 Answers2

1

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
Peter
  • 8,776
  • 6
  • 62
  • 95
Md Hasibur Rahaman
  • 1,041
  • 3
  • 11
  • 34
0

This way of printing doesn't really need array_map. The following uses the biggest part of your own function. It is untested but should help you in the right direction.

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

    return $string;
}

echo print_array($myArray);
Peter
  • 8,776
  • 6
  • 62
  • 95