What is the json_encode function in PHP?
Overview
The
In PHP we can convert arrays into JSON format. Both indexed and associative arrays can be converted. This conversion is done using the json_encode() method in PHP, which converts a value into a JSON object.
Syntax
json_encode($value, options,depth)
Parameters
$value: This represents the value/variable to be encoded.options: Theflagsoroptionsparameter is to specify options that you wish to apply to the method.depth: Depth has a maximum value of 512 and must be greater than zero.
Returns
This method returns the JSON object of the value parsed.
Code
In the code below, the array variables $indexArray and $assocArray will be converted into JSON objects.
<?php//An index array$indexArray = array("Volvo", "BMW", "Toyota");//associative array$assocArray = array("Peter"=>35, "Ben"=>37, "Joe"=>43);// A string value$aStringVal = "I am encoding this string";$a = json_encode($indexArray) ;$b = json_encode($assocArray) ;$c = json_encode($aStringVal) ;echo $a . "\n";echo $b . "\n";echo $c . "\n";?>