Reputation: 4150
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
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
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
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.
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
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
Reputation: 22061
<script type="text/javascript">
alert(<?=print_r($array)?>);
</script>
Upvotes: 2
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