novactown.com
novactown.com

Reputation: 125

PHP array to echo javascript array that I can access?

I have a php array called $user.

At the minute I am getting the variables across to javascript by manually adding them like so.

var username = ' . $user['username'] . ';

And so on is there a way I can make php echo a javascript array that I can access?

Upvotes: 0

Views: 73

Answers (2)

Jaffa
Jaffa

Reputation: 12710

Have you tried json_encode ?

<?php echo json_encode ( $array ); ?>

See the documentation here.

Upvotes: 1

Matt
Matt

Reputation: 9433

You're looking for json_encode

PHP:

$json_user = json_encode($user);

JavaScript:

var user = JSON.parse('<?php echo $json_user; ?>');

That's untested code but the idea behind it is sound

Upvotes: 4

Related Questions