php array to javascript array – How to Convert PHP Array to JavaScript Array?

php array to javascript array – You can easily use PHP array in javascript you only need to convert PHP array into JSON format Using json_encode() function.

php array to javascript array

You can use PHP array in JavaScript. PHP array can be used in js, whatever the array is a single or multidimensional or indexed or associative array.

Here you will see converting single dimensional PHP array into javaScript array by using json_encode($yourArrName).

How to Convert PHP Array to JavaScript Array?

Single Dimensional Indexed Array
PHP

$memberArray = array('virat Kohali', '[email protected]');

JavaScript:

<script type="text/javascript">
var members = <?php echo json_encode($memberArray); ?>;
</script>

Access Array Elements in JavaScript:

alert(members[0]); //results will be "virat Kohali"

How to convert PHP array to JavaScript array?

Read Also:  Laravel requires the Mcrypt PHP extension

Example

<?php
$memberArray = array('Kanji', 'virat', 'dharmik');
?>

<script type="text/javascript">
    var members = <?php echo json_encode($memberArray);?>;
    console.log(members[0]);
    // results: Kanji
</script>

Don’t Miss : Json To Array Php Examples

Multidimensional Indexed Array

PHP:

$memberArray = array(
    array('virat Kohali', '[email protected]'),
    array('Krunal Sisodiya', '[email protected]'),
    array('Samsung Sanju', '[email protected]')
);

JavaScript:

<script type="text/javascript">
var members = <?php echo json_encode($memberArray); ?>;
</script>

Access Array Elements in JavaScript:

alert(members[1][0]); //output will be "Krunal Sisodiya"

Multidimensional Associative array

PHP:

$memberArray = array(
    array('name'=>'virat Kohali', 'email'=>'[email protected]'),
    array('name'=>'Krunal Sisodiya', 'email'=>'[email protected]'),
    array('name'=>'Samsung Sanju', 'email'=>'[email protected]')
);

JavaScript:

<script type="text/javascript">
var members = <?php echo json_encode($memberArray); ?>;
</script>

alert(members[0].email); //output will be "[email protected]"

Multidimensional associative array

<?php
$memberArray = array(
    array(
        'name' => 'Kanji',
        'email' => '[email protected]'
    ),
    array(
        'name' => 'virat',
        'email' => '[email protected]'
    ),
    array(
        'name' => 'dharmik',
        'email' => '[email protected]'
    )
);
?>
<script type="text/javascript">
    var members = <?php echo json_encode($memberArray);?>;
    console.log(members[1].name);
    // results: virat
</script>

I hope you get an idea about php array to javascript array.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.