Dan
Dan

Reputation: 4150

PHP - Convert a multidimensional array to string?

I'm working on a small ajax application and need to see if the values being generated in the background are what is expected. The value returned by the quest can be quite a complex multidimensional array, is there a way to convert this into a string so that it can be shown with alert?

Is there any other way of seeing these values?

Any advice appreciated.

Thanks.

Upvotes: 15

Views: 37674

Answers (8)

knittl
knittl

Reputation: 265918

print_r, var_dump or var_export are good candidates. When writing a REST service, you might also want to look at json_encode.

Upvotes: 30

kachmi
kachmi

Reputation: 43

Here is a simple answer in PHP:

function implode_recur($separator, $arrayvar) {
    $output = "";
    foreach ($arrayvar as $av)
    if (is_array ($av)) 
        $out .= implode_recur($separator, $av); // Recursive array 
    else                   
        $out .= $separator.$av;

    return $out;<br>
}

$result = implode_recur(">>",$variable);

Upvotes: 1

WilliamStam
WilliamStam

Reputation: 304

i work on a bunch of ajax apps.. in firefox i have an "add-on" called JSON view

then all my projects have a function

function test_array($array) {
    header("Content-Type: application/json");
    echo json_encode($array);
    exit();
}

so whenever i want to see what the output is i just go test_array($something) and it shows me the results.

screenshot

its made debugging a breaze now

PS. know this Q is ancient and im not really answering the origional posters Q but might be useful for someone else aswell

Upvotes: 4

Ahmad Balavipour
Ahmad Balavipour

Reputation: 31

I found this function useful:

function array2str($array, $pre = '', $pad = '', $sep = ', ')
{
    $str = '';
    if(is_array($array)) {
        if(count($array)) {
            foreach($array as $v) {
                $str .= $pre.$v.$pad.$sep;
            }
            $str = substr($str, 0, -strlen($sep));
        }
    } else {
        $str .= $pre.$array.$pad;
    }

    return $str;
}

from this address: http://blog.perplexedlabs.com/2008/02/04/php-array-to-string/

Upvotes: 1

user187291
user187291

Reputation: 53960

you can also consider FirePHP http://www.firephp.org

Upvotes: -3

Roch
Roch

Reputation: 22061

<script type="text/javascript">
alert(<?=print_r($array)?>);
</script>

Upvotes: 2

J__
J__

Reputation: 3837

The implode command returns an array as a string.

Upvotes: -1

soulmerge
soulmerge

Reputation: 75774

If you want to show it with javascript, I would recommend json_encode(), everything else has been covered by knittl's answer.

Upvotes: 7

Related Questions