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

Sign up to request clarification or add additional context in comments.

Comments

1

Have you tried json_encode ?

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

See the documentation here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.