0

I have this javascript array

   <script>
$(function() {
 var foo= [ "one",
            "two",
            "three",
            "one",
            "final"];
</script>

Now, I am trying to replace the foo with a PHP array.

<?php $array = array("sky","mac","rain","bob","sep","ion"); ?>

Now, I tried

<script>
    $(function() {
     var foo= [<?php array("sky","mac","rain","bob","sep","ion"); ?> ];
    </script>

But, it seems not to be working

3
  • You forgot echoing the array's content?! Commented Mar 3, 2013 at 12:43
  • 1
    You can't just echo an array. Commented Mar 3, 2013 at 12:45
  • This is the ideal use case for the json_encode function. Commented Mar 3, 2013 at 12:46

2 Answers 2

6

IN PHP you can use the method json_encode() to convert most PHP arrays into JSON, which is a legit object in JavaScript.

<?php $array = array("sky","mac","rain","bob","sep","ion"); ?>

<script>
// ...
var foo = <?php echo json_encode( $array ); ?>;
// ...
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

What is the benefit of this rather than the previous answer? @Sirko
See my comment below the previous answer.
@Simon Less verbose. Usage of a built-in-method almost always is better than reinventing the wheel. The same command can be used to transfer multi-level-arrays / objects. ...
@Sirko thanks, I've learned a new thing today. But, the I wanted to use this code for another project, and got another problem. I guess I'll ask a new question. Help if you can pls.
0
var foo= ['<?php print implode("','", array("sky","mac","rain","bob","sep","ion")); ?>'];

2 Comments

This does not guarantee the values being properly escaped/encoded for JavaScript. json_encode() should be used in stead as suggested in the other answer
For example, if the PHP array contains ', rest of the JavaScript will me messed up.

Your Answer

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