How to convert PHP array to JavaScript array
Today we’ll explain to you how to convert PHP array to JavaScript array. Sometimes, we need to pass a PHP array in JavaScript that can be a single or multidimensional or indexed or associative array. Mostly, we pass PHP data in an Ajax request, at that time it is useful.
Using the json_encode() function, we can easily convert a PHP array to a JavaScript array and it is accessible in JavaScript.
Convert the different types of an array
Let’s start with examples.
1. Single dimensional indexed array
Here, we will convert the PHP numeric array to JavaScript array as shown below in the code.
PHP
<!--?php
$studentArray = array('Denny', 'John', 'Aien');
?-->
JavaScript
<script type="text/javascript">
var students = <?php echo json_encode($studentArray);?>;
console.log(students[0]);
// Output: Denny
</script>
2. Multidimensional indexed array
Now, we will take an example to convert a PHP multidimensional indexed array to a JavaScript array.
PHP
<!--?php
$studentArray = array(
array('Denny', '[email protected]'),
array('John', '[email protected]'),
array('Aien', '[email protected]')
);
?-->
JavaScript
<script type="text/javascript">
var students = <?php echo json_encode($studentArray);?>;
console.log(students[2][1]);
// Output: [email protected]
</script>
3. Multidimensional associative array
Lastly, let’s take an example to convert a PHP multidimensional associative array to a JavaScript array.
PHP
$studentArray = array(
array(
'name' => 'Denny',
'email' => '[email protected]'
),
array(
'name' => 'John',
'email' => '[email protected]'
),
array(
'name' => 'Aien',
'email' => '[email protected]'
)
);
?>
JavaScript
<script type="text/javascript">
var students = <?php echo json_encode($studentArray);?>;
console.log(students[1].name);
// Output: John
</script>
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂