PHP: json_encode() function | How to convert PHP Arrays to JSON

By Parth Patel on Sep 10, 2021

In last tutorial, we talked about how to convert JSON to PHP arrays using json_decode() function. In this tutorial, we will learn how to convert PHP arrays to JSON therefore we can pass PHP array to javascript easily.

Syntax:

json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false

Parameters:

  • value: It is the value being passed to the function to be encoded to json string. It can be of any type except Resource type. Normally, you would pass PHP array to convert it to JSON string. All string data must be valid UTF-8 encoded.
  • flag: It is a bitmask consisting of JSON constants like JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE which can affect how function encodes the given value.
  • depth: It sets the maximum depth of the given value (array), the function can work with. By default, it is set to 512, must be greater than 0.

Return:

The json_encode() function returns JSON encoded string if the function succeeded or if it fails, then it will return false.

Examples

How to Convert PHP String to JSON

Let's see how you can convert a PHP string to JSON. It will return string as is, since string is a valid value in JSON.

<?php

$string = "Hello World!";

echo json_encode($string);

?>

Output:

"Hello World!"

How to Convert PHP Array to JSON

This is the most common usecase. Let's see how we can convert PHP array into JSON string and therefore, we can pass PHP array to Javascript as JSON-encoded string.

<?php

$user = array('name' => 'John Doe', 'email' => 'john@doe.com');

echo json_encode($user);

?>

Output:

{"name":"John Doe","email":"john@doe.com"}

How to Convert PHP Object to JSON

We can also convert PHP Objects to JSON string. It will use object properties as keys and will return JSON encoded string.

You can see that array and object both will yield to same JSON string.

<?php

class User {
	public $name;
	public $email;
}

$user = new User();

$user->name = 'John Doe';

$user->email = 'john@doe.com';

$json = json_encode($user);

echo $json;

?>

Output:

{"name":"John Doe","email":"john@doe.com"}

Conclusion

In a nutshell, we learned how json_encode() function works, and also checked some examples on how to convert PHP values to JSON which we can pass it to javascript as well.

Happy coding!

Adios.