Below is my code where the php array $keys assigned to a JS array var keysArr, But the value display on the alert box is not correct.

Thus, there is something wrong on assign Php array to Js array.

Can anyone help me? Thanks in advance!

<?php
$keys = array(1, 2, 3, 4);
?>
<html>
    <head>
    <script type="text/javascript">
        var keysArr = <?php print $keys?>;
        for (var i = 0; i < keysArr.length; ++i){

                    alert(keysArr[i]);

        }
    </script>
    </head>
    <body>
    </body>
</html>
link|improve this question

37% accept rate
feedback

3 Answers

up vote 0 down vote accepted

Try this

<?php
$keys = array(1, 2, 3, 4);
?>
<html>
    <head>
    <script type="text/javascript">
        var keysArr = Array(<?php echo implode(',',$keys);?>);
        for (var i = 0; i < keysArr.length; ++i){

                    alert(keysArr[i]);

        }
    </script>
    </head>
    <body>
    </body>
</html>

whith print you're just showing Array, and not proper array code for js. Look inside the HTML you generate.

link|improve this answer
4  
That will break horribly for any array containing non-Number data or any array consisting of just one value. – Quentin Nov 8 '11 at 12:38
yes, youre right. It will only work for arrays containg more than one number. – Kokers Nov 8 '11 at 12:44
feedback
var keysArr = <?php json_encode($keys) ?>;

requires PHP >= 5.2.0, but third-party json_encode() implementations are available for older versions.

link|improve this answer
feedback

Try this, it doesn't need JSON extension:

var keysArr = [ <?php print implode(',', $keys); ?> ];
    for (var i = 0; i < keysArr.length; ++i){
        alert(keysArr[i]);
    }
link|improve this answer
2  
That will break horribly for any array containing non-Number data – Quentin Nov 8 '11 at 12:39
I'm sorry, my mistake. – fonini Nov 8 '11 at 12:54
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.