1. json_decode() — Associative Arrays vs stdClass Objects

By default, `json_decode($jsonString)` converts JSON objects into instances of `stdClass`. Passing `true` as the second argument (`assoc`) instructs PHP to convert all JSON objects into native PHP associative arrays.

Decoding JSON to Associative Arrays in PHP 8
<?php
$json = '{"name": "Dev Studio", "active": true, "tags": ["php", "json"]}';

// 1. Decodes to stdClass Object
$objectData = json_decode($json);
echo $objectData->name; // "Dev Studio"

// 2. Decodes to Associative Array (Recommended)
$arrayData = json_decode($json, true);
echo $arrayData['name']; // "Dev Studio"
Explanation: Using associative arrays simplifies array iteration and integration with Laravel array helpers.

2. Strict Error Handling with JSON_THROW_ON_ERROR

In legacy PHP versions, passing malformed JSON to `json_decode()` silently returned `null`. In PHP 7.3+, pass the `JSON_THROW_ON_ERROR` flag to automatically throw a `JsonException` on syntax failure.

Catching JsonException in Try-Catch Blocks
<?php
try {
    // Malformed JSON (unquoted key)
    $invalidJson = '{name: "Invalid"}';
    $data = json_decode($invalidJson, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo "JSON Error Caught: " . $e->getMessage();
    // Output: JSON Error Caught: Syntax error
}
Explanation: JSON_THROW_ON_ERROR prevents subtle bugs caused by unchecked null return values.

3. Preserving UTF-8 & Special Characters with json_encode()

By default, `json_encode()` escapes non-ASCII characters into Unicode escape sequences (e.g. `\u00e9`). Pass `JSON_UNESCAPED_UNICODE` and `JSON_UNESCAPED_SLASHES` to preserve human-readable UTF-8 text and URL slashes.

Clean UTF-8 JSON Encoding Output
<?php
$payload = [
    'title' => 'Café & Restaurant',
    'url' => 'https://prettyjson.in/json-formatter'
];

// Encode with clean flags & pretty indentation
$jsonOutput = json_encode(
    $payload,
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT
);

echo $jsonOutput;
Explanation: JSON_PRETTY_PRINT formats PHP array output with 4-space indentation.