You will be glad to hear that every PHP variable can be used in Javascript, whatever variable is a single value or array (array can be multidimensional or indexed or associative). You can easily convert PHP array to JavaScript array. Simply Using PHP json_encode() or implode() function, any PHP array can be converted to a javascript array and used in JavaScript. Below you can see multiple examples of Convert PHP Array to JavaScript Array.
Convert Single Dimensional PHP Array to JavaScript Array:
In a beginning example, we are converting Single Dimensional PHP Array to JavaScript Array. First, we need a PHP Array which is
$array = array('Tutorials Bites', 'info@tutorialsbites.com');
Get above array in javascript by using
<script type="text/javascript">
var info = <?php echo json_encode($array); ?>;
</script>
We stored PHP array values in the javascript info variable. Now You can access array elements in javascript by using
alert(info[0]); //output will be "Tutorials Bites"
//or
console.log(info[0]); //output will be "Tutorials Bites"
you can also print in the loop by using this code
<script type="text/javascript">
// Display all elements by using loop
for(var i = 0; i < info.length; i++){
console.log(info[i]);
}
</script>
Method 2 :
<script type="text/javascript">
// Using PHP implode() function
var convertedArray = <?php echo '["' . implode('", "', $info. '"]' ?>;
// Printing the array elements
console.log(convertedArray);
</script>
Notice: Your javascript code must be below of php code.
Convert Multidimensional Associative Array to JavaScript Array:
In addition example, we are converting Single Dimensional PHP Array to JavaScript Array. Same we need an array which is
$array = array(
array('name'=>'Abdul', 'email'=>'abdul@tutorialsbites.com'),
array('name'=>'Ali', 'email'=>'ali@tutorialsbites.com'),
array('name'=>'Zain', 'email'=>'zain@tutorialsbites.com')
);
<script type="text/javascript">
var info = <?php echo json_encode($array); ?>;
alert(info[0].email); //output will be "abdul@tutorialsbites.com"
Or
console.log(info[0].email); //output will be "abdul@tutorialsbites.com"
</script>
Read more about JQuery Multiselect Dropdown with custom icon
Read more about How to convert PHP Array to JavaScript Array
How to convert PHP Array to JavaScript Array?
<script type=”text/javascript”>
var info = (php tag start) echo json_encode($array); (php tag end)
</script>
How to convert php array to javascript object
var info = (php tag start) echo json_encode($array); (php tag end)
Then get your desired index object value like this alert(info[0]);
Its helps alot. Thanks
Very easy to understand tutorial. Love it!
Really appreciate your effort