Pass PHP arrays to javascript using JSON

PHP

JSON(JavaScript Object Notation) which is used for exchanging and storing data. JSON is a text, using JSON convert the exchanging data to text between browser and server. PHP has some built-in functions to handle JSON.

json_encode():which coverts a PHP value into a JSON value and it returns a string.

We can use json_encode function to covert a PHP array. In this tutorial we can see PHP indexed and associative array value into JSON value using json_encode.

PHP indexed array

For example: Indexed array:–

1
2
3
4
5
6
<?php$arr_color = array('Red','Green','Blue');
echo json_encode($arr_color); //return ["Red","Green","Blue"]?>
<script>
var color = <?php echo json_encode($arr_color) ?>;
alert(color[0]);  //return Red
</script>

In the above example,PHP indexed array is given. Use this PHP array values in javascript by using JOSN json_encode() function. Then we can fetch PHP array values in javascript.

json_encode() In PHP associative array

Here I am going explain how to pass PHP associative array to javascript using JSON. First declare a php Associative array. Then in javascript encode this array using json_encode() function. After that we can simply use the php array in javascript. Either we can fetch the array values using arrayname.index or arrayname[‘index’]. these two methods are shown in the example. Please take a look.

Example for Associative arrays:–

1
2
3
4
5
6
7
8
9
10
11
<?php 
    $arr_color = array('clr1'=>'Red','clr2'=>'Green','clr3'=>'Blue');
 echo json_encode($arr_color);//return  {"clr1":"Red","clr2":"Green",
"clr3":"Blue"}
<?>
<script>
var color = <?php echo json_encode($arr_color) ?>;
alert(color.clr2);  OR alert(color['clr2']) //Both return Green
</script>

PHP associative array becomes represented as object in Javascript .

Leave a Reply

Your email address will not be published. Required fields are marked *