0

I have a php array that I also want my javascript code to use. I don't want to keep having to edit both the php and javascript code all the time to keep the array current.

Is there a way to translate that array to a file and have javascript and php convert that file to an array and read from the file? How do we convert a file lines into an array in javascript?

3 Answers 3

3

Use JSON:

<?php

$arr = array('foo', 'bar', 'baz');

?>

<script type="text/javascript">
    var arr = <?php echo json_encode($arr); ?>;
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

Use JSON.

Some useful links: http://php.net/json, http://www.json.org/js.html, http://www.dyn-web.com/tutorials/php-js/json.php

Comments

0

JavaScript's array/object syntax is equal to the json syntax, so you can simply use json_encode in PHP and echo that, as PHP is run on the server and JavaScript in the browser:

var my_nice_js_var = <?php echo json_encode($phpArray) ?>

Update: to do this in a JS file, call your file the-file.php and then add this add the top:

<?php header('Content-Type: text/javascript') ?>

1 Comment

Problem is this is in a .js file. Can't intermix php and js.

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.