JSON
JSON (JavaScript Object Notation) is a lightweight, text-based data format used to store and exchange structured data. Despite its name, JSON is not tied to JavaScript as a language. It simply uses a syntax that was inspired by JavaScript object literals because they are easy to read and write. JSON itself contains no logic, functions, or behavior; it is purely data.
Because JSON is plain text, it is ideal for communication between systems. A server can send JSON to a browser, another server, or a mobile app, regardless of the programming language used on either side. This makes JSON one of the most common formats for APIs and data exchange.
PHP provides built-in support for JSON through two core functions: json_encode() and json_decode().
The json_encode() function converts a PHP value into a JSON-formatted string. When encoding an associative array, PHP produces a JSON object with key-value pairs. When encoding an indexed array, PHP produces a JSON array. The result of json_encode() is always a string, not a PHP array or object.
The json_decode() function performs the opposite operation. It takes a JSON string and converts it into a PHP data structure. By default, json_decode() returns a PHP object where JSON keys become object properties. When the second parameter of json_decode() is set to true, the JSON object is converted into an associative array instead.
Accessing decoded JSON depends on how it was decoded. When decoded as an object, values are accessed using the object property operator (->). When decoded as an associative array, values are accessed using array syntax with square brackets.
Decoded JSON data can be iterated using foreach, whether it is an object or an associative array. In both cases, the loop provides access to each key and its corresponding value.
The key idea is that JSON acts as a bridge format between systems. PHP does not treat JSON as JavaScript, but as structured text that can be encoded from PHP values or decoded back into PHP objects or arrays for further processing.