PHP Function to Convert Array to JSON
This article explains how to convert a PHP array into a JSON string using the built-in PHP function. You will learn the exact function to use, its syntax, practical code examples, and how to format the resulting JSON output.
The json_encode()
Function
In PHP, the json_encode() function is
used to convert an array (or an object) into a JSON string
representation. This function is essential for sending data from a PHP
backend to a JavaScript frontend, API endpoints, or mobile
applications.
Basic Syntax
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false$value: The value being encoded. This is typically an associative or indexed array.$flags: Optional bitmask constants that modify the encoding behavior (e.g., formatting).$depth: Optional maximum depth. Must be greater than zero.- Return Value: Returns a JSON-encoded string on
success, or
falseon failure.
Code Examples
1. Converting an Associative Array
An associative array in PHP converts into a JSON object.
<?php
// Define an associative array
$user = [
"name" => "John Doe",
"email" => "john@example.com",
"age" => 30,
"isAdmin" => true
];
// Convert array to JSON string
$jsonString = json_encode($user);
// Output the JSON string
echo $jsonString;
?>Output:
{"name":"John Doe","email":"john@example.com","age":30,"isAdmin":true}2. Converting an Indexed Array
A simple indexed array in PHP converts into a JSON array.
<?php
// Define an indexed array
$colors = ["red", "green", "blue"];
// Convert array to JSON string
$jsonString = json_encode($colors);
echo $jsonString;
?>Output:
["red","green","blue"]Useful Flags for
json_encode()
You can pass specific constants as the second argument to customize the JSON string output:
JSON_PRETTY_PRINT: Uses whitespace to format the returned data for human readability.JSON_UNESCAPED_SLASHES: Prevents PHP from escaping forward slashes (/).JSON_NUMERIC_CHECK: Encodes numeric strings as numbers instead of strings.
Example with Flags:
<?php
$data = [
"url" => "https://example.com/api",
"status" => "200"
];
// Use flags to pretty print and prevent escaped slashes
$jsonString = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
echo $jsonString;
?>Output:
{
"url": "https://example.com/api",
"status": 200
}