PHP How to Convert Array to JSON String
json_encode() function in PHP to convert an array to a JSON string, like json_encode($array).Examples
How to Think About It
json_encode() that takes your array and changes it into a JSON string automatically.Algorithm
Code
<?php $array = ['name' => 'Alice', 'age' => 25, 'city' => 'Paris']; $json = json_encode($array); echo $json; ?>
Dry Run
Let's trace converting ['name' => 'Alice', 'age' => 25, 'city' => 'Paris'] to JSON.
Input array
array = ['name' => 'Alice', 'age' => 25, 'city' => 'Paris']
Call json_encode
json_encode(array) returns '{"name":"Alice","age":25,"city":"Paris"}'
Output JSON string
Output: '{"name":"Alice","age":25,"city":"Paris"}'
| Step | Action | Value |
|---|---|---|
| 1 | Input array | {"name":"Alice","age":25,"city":"Paris"} |
| 2 | Call json_encode | {"name":"Alice","age":25,"city":"Paris"} |
| 3 | Output JSON string | {"name":"Alice","age":25,"city":"Paris"} |
Why This Works
Step 1: Built-in function
PHP provides json_encode() to convert arrays or objects into JSON strings easily.
Step 2: Input array
You pass your PHP array to json_encode() as the input parameter.
Step 3: Output JSON
The function returns a string formatted as JSON, which can be used for data exchange or storage.
Alternative Approaches
<?php $array = ['a', 'b']; $json = '[' . implode(',', array_map(fn($v) => '"' . $v . '"', $array)) . ']'; echo $json; ?>
<?php $array = ['name' => 'Bob', 'age' => 28]; $json = json_encode($array, JSON_PRETTY_PRINT); echo $json; ?>
Complexity: O(n) time, O(n) space
Time Complexity
The function processes each element of the array once, so time grows linearly with array size.
Space Complexity
The output JSON string size depends on the input array size, requiring additional memory proportional to input.
Which Approach is Fastest?
Using PHP's built-in json_encode() is fastest and safest compared to manual string building.
| Approach | Time | Space | Best For |
|---|---|---|---|
| json_encode() | O(n) | O(n) | All array to JSON conversions |
| Manual string building | O(n) | O(n) | Simple flat arrays only, not recommended |
| json_encode() with options | O(n) | O(n) | Readable JSON output |
json_encode() to safely convert arrays to JSON in PHP.json_encode() leads to errors and invalid JSON.