0

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?

1
  • You should use JavaScript Object Notation (JSON) like they suggested blow. Unless you need to use the array in a for loop, in which case, an associative array may not be a good choice. Commented Jan 17, 2012 at 15:47

2 Answers 2

4

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

0
1

Have you tried json_encode ?

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

See the documentation here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.