Open In App

How to Encode Array in JSON PHP ?

Encoding arrays into JSON format is a common task in PHP, especially when building APIs or handling AJAX requests.

Below are the approaches to encode arrays into JSON using PHP:

Using json_encode()

PHP provides a built-in function json_encode() to encode PHP data structures, including arrays, into JSON format. It automatically handles most data types, making it simple and efficient.

Example: The example below shows How to encode an array in JSON PHP Using json_encode().

<?php
// code
$array = ["name" => "John", "age" => 30, "city" => "New York"];
echo json_encode($array);
?>

Output
{"name":"John","age":30,"city":"New York"}

Encoding Associative Arrays

Associative arrays, also known as key-value pairs, are commonly used in PHP. When encoding associative arrays into JSON, the keys become the property names, and the values become the property values in the resulting JSON object.

Example: The example below shows How to encode an array in JSON PHP Using Encoding Associative Arrays.

<?php
// code
$assocArray = ["name" => "Jane", "age" => 25, "city" => "Los Angeles"];
echo json_encode($assocArray);
?>

Output
{"name":"Jane","age":25,"city":"Los Angeles"}

Custom JSON Serialization

In this approach, PHP jsonSerialize() method allows you to implement custom JSON serialization for your objects. In some cases, you may need more control over the JSON output, such as converting objects or complex data structures into JSON.

Example: The example below shows How to encode an array in JSON PHP Using Custom JSON Serialization.

<?php
class Person implements \JsonSerializable
{
    public $name;
    public $age;

    public function jsonSerialize()
    {
        return [
            "name" => $this->name,
            "age" => $this->age,
        ];
    }
}

$person = new Person();
$person->name = "Alice";
$person->age = 35;

echo json_encode($person);

?>

Output
{"name":"Alice","age":35}
Article Tags :