Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use php array in jquery

you can see my goal here,

i have a php array in my code like

<?php $myvalues = array(13,45,23,54,767,234,543,245); ?>

i want to store all the values in jquery array in my script

<script>
    $(document).ready(function(){
      var jqueryarray = $myvalues; // here i want to store $myvalues array values in jqueryarray
        for (var i = 0; i < jqueryarray.length; i++) {
            //my stuf
        };
    }); 
</script>

How can i do this one ?

Any ideas ?

like image 833
Naresh Avatar asked Apr 09 '14 05:04

Naresh


People also ask

How to use PHP array in js?

You can easily use PHP array in javascript you only need to convert PHP array into JSON format Using json_encode() function. PHP array can be converted to JavScript array and accessible in JavaScript. Whatever the array type is, a single or multidimensional or indexed or associative array.


3 Answers

You can use json_encode,

var jqueryarray = <?php echo json_encode($myvalues); ?>;
like image 58
Rikesh Avatar answered Oct 20 '22 00:10

Rikesh


Try this:

var jqueryarray = JSON.parse('<?php echo json_encode($myvalues); ?>');
like image 20
Deepak Mane Avatar answered Oct 19 '22 23:10

Deepak Mane


Pretty simple and you were almost there. Use the below code and of course in php file

<?php $myvalues = array(13,45,23,54,767,234,543,245); ?>
<script>
    $(document).ready(function() {
        var jqueryarray = <?php echo json_encode($myvalues ); ?>;
        for (var i = 0; i < jqueryarray.length; i++) {
            console.log(jqueryarray[i]);
        }
        ;
    });
</script>
like image 43
solvease Avatar answered Oct 20 '22 00:10

solvease