PHP array can be passed to a JavaScript function using json_encode with the below lines of code −
<script> var var_name= <?php echo json_encode($php_variable); ?>; </script>
If an object needs to be parsed from JSON like string (required in AJAX request), the below lines of code can be used −
var my_data = "<JSON-String>"; var my_var = JSON.parse(my_data);
Example
Let us see an example −
<?php
// Create a PHP array
$sample_array = array(
0 => "Hello",
1 => "there",
)
?>
<script>
// Access the elements of the array
var passed_array = <?php echo json_encode($sample_array); ?>;
// Display the elements inside the array
for(var i = 0; i < passed_array.length; i++){
document.write(passed_array[i]);
}
</script>Output
This will produce the following output −
Hellothere