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.
The following example converts numerically indexed PHP array to JavaScript array.
PHP:
$userArray = array('John Doe', 'john@example.com');
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"
The following example converts numerically indexed PHP multidimensional array to JavaScript array.
PHP:
$userArray = array(
array('John Doe', 'john@example.com'),
array('Marry Moe', 'marry@example.com'),
array('Smith Watson', 'smith@example.com')
);
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"
The following example converts associative PHP multidimensional array to JavaScript array.
PHP:
$userArray = array(
array('name'=>'John Doe', 'email'=>'john@example.com'),
array('name'=>'Marry Moe', 'email'=>'marry@example.com'),
array('name'=>'Smith Watson', 'email'=>'smith@example.com')
);
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 "john@example.com"