How to Convert PHP Array to JavaScript Array

PHP array can be used in JavaScript, whatever the array is a single or multidimensional or indexed or associative array. You can convert PHP array to JavaScript array easily with a single line of code. Using json_encode() function, PHP array can be converted to JavScript array and accessible in JavaScript.

Single Dimensional Indexed Array

The following example converts numerically indexed PHP array to JavaScript array.
PHP:

$userArray = array('John Doe''[email protected]');

JavaScript:

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

Access Array Elements in JavaScript:

alert(users[0]); //output will be "John Doe"

Multidimensional Indexed Array

The following example converts numerically indexed PHP multidimensional array to JavaScript array.
PHP:

$userArray = array(
    array(
'John Doe''[email protected]'),
    array(
'Marry Moe''[email protected]'),
    array(
'Smith Watson''[email protected]')
);

JavaScript:

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

Access Array Elements in JavaScript:

alert(users[1][0]); //output will be "Marry Moe"

Multidimensional Associative array

The following example converts associative PHP multidimensional array to JavaScript array.
PHP:

$userArray = array(
    array(
'name'=>'John Doe''email'=>'[email protected]'),
    array(
'name'=>'Marry Moe''email'=>'[email protected]'),
    array(
'name'=>'Smith Watson''email'=>'[email protected]')
);

JavaScript:

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

Access Array Elements in JavaScript:

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

Related Articles

Comments 0