The php json_encode() function allows us to get the JSON representation of variables.
class exampleClass {
public $id;
private $name;
static protected $multiplyNumbers;
static function multiplyNumbers($a,$b) {
return $a * $b;
}
}
$num = 5;
$string = "This is a string";
$array = ["This","is","an","array"];
echo json_encode(new exampleClass) . "n";
echo json_encode($num). "n";
echo json_encode($string). "n";
echo json_encode($array). "n";
//Output:
{"id":null}
5
"This is a string"
["This","is","an","array"]
When working with variables, the ability to easily convert a variable to JSON and get the JSON representation of a variable is very useful.
The php json_encode() function returns the JSON representation of a variable in a string. json_encode() is similar to the JavaScript stringify() function.
We can use json_encode() to convert strings, ints, floats, arrays and objects to JSON.
Below are some examples of using json_encode() to convert different variables to JSON in php.
class exampleClass {
public $id;
private $name;
static protected $multiplyNumbers;
static function multiplyNumbers($a,$b) {
return $a * $b;
}
}
$num = 5;
$string = "This is a string";
$array = ["This","is","an","array"];
echo json_encode(new exampleClass) . "n";
echo json_encode($num). "n";
echo json_encode($string). "n";
echo json_encode($array). "n";
//Output:
{"id":null}
5
"This is a string"
["This","is","an","array"]
If you want to change how encoding happens, there are many JSON constants available for you to use.
Printing Arrays in php with json_encode() Function
We can print an array in php is with the help of the php json_encode() function.
If you have an array, you can pass it to json_encode() and get the JSON representation of the array.
Below is an example in php showing how to print an array with the help of json_encode().
$array = ["This","is","an","array"];
echo json_encode($array);
//Output:
["This","is","an","array"]
Printing Objects in php with json_encode() Function
If you have an object, you can pass it to print_r() and get a JSON representation of the object. json_encode() will show the public variables, but not private variables of the object.
Below is an example in php showing how to print an object with json_encode().
class exampleClass {
public $id;
private $name;
static protected $multiplyNumbers;
static function multiplyNumbers($a,$b) {
return $a * $b;
}
}
echo json_encode(new exampleClass);
//Output:
{"id":null}
Hopefully this article has been useful for you to learn how to use json_encode() in your php code.