PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
110: json_encode and json_decode Options
By now, you've likely used json_encode and json_decode a dozen times. They seem straightforward: one turns a PHP variable into a string, and the other turns that string back into a variable. But if you're just calling them without any options, you're essentially playing a game of "I hope the data is formatted exactly how I expect," which is a recipe for a 3:00 AM production bug.
The Object vs. Array Headache
The most common mistake I see is the naive use of json_decode($json). By default, this returns a stdClass object. Now, objects are fine, but in PHP, we spend most of our time manipulating associative arrays. When you get an object back, you're forced to use the -> syntax. This sounds trivial until you're trying to iterate over the data or pass it into a function that expects an array.
// The naive way
$data = json_decode($json_string);
echo $data->user->name; // This works, but it's rigid.
I always recommend passing true as the second argument. This tells PHP to convert everything into an associative array. It makes the data much more flexible to work with, especially when you're using array functions like array_map or array_filter. It's a small change, but it saves you from constantly casting objects to arrays later in your pipeline.
// The better way
$data = json_decode($json_string, true);
echo $data['user']['name']; // Much more natural for PHP developers.
Silent Failures and the Modern Fix
Here is where things get dangerous. Traditionally, if json_decode failed because of a syntax error in the JSON string, it would simply return null. If you weren't explicitly checking json_last_error() after every single call—which, let's be honest, almost nobody does—your code would just keep running with a null value until it hit a "trying to access array offset on value of type null" error five functions later. Tracking that back to the source is a nightmare.
Since PHP 7.3, we have JSON_THROW_ON_ERROR. I consider this mandatory. Instead of returning null and hoping for the best, this flag forces PHP to throw a JsonException. I'd much rather have my application crash immediately with a clear error message than have it silently fail and corrupt a database record because a comma was missing in the API response.
// The risky way
$data = json_decode($json_string, true);
// If $json_string is malformed, $data is null. Silence.
// The professional way
try {
$data = json_decode($json_string, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
// Log it, alert the team, or return a 400 Bad Request
error_log("JSON Decode Error: " . $e->getMessage());
}
Handling Unicode and Human Readability
When you're encoding data to send to a browser, json_encode($data) is usually enough. But what happens when your data contains accented characters or emojis? By default, PHP escapes these as Unicode sequences (like \u00e9). While this is technically correct and safe, it's a pain to debug in your logs.
If you're writing JSON to a log file or a config file that a human needs to read, use JSON_PRETTY_PRINT and JSON_UNESCAPED_UNICODE. The first adds whitespace and indentation, and the second keeps your characters as they are. I've spent way too many hours staring at a wall of minified JSON trying to find a missing key; pretty-printing is a gift to your future self.
$user_profile = [
'name' => 'André',
'bio' => '🚀 Software Engineer',
'settings' => ['theme' => 'dark', 'notifications' => true]
];
// Naive: one long, escaped string
echo json_encode($user_profile);
// Better: Readable and clean
echo json_encode($user_profile, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
Just keep in mind that JSON_PRETTY_PRINT increases the payload size. Don't use it for high-traffic API responses where every byte counts, but absolutely use it for debugging and configuration files.
📋 Practical Task
Exercise: Robust API Response Parser
You are building a module that consumes a Product Catalog API. The API is known to be flaky—sometimes it sends malformed JSON, and the product descriptions often contain special characters and emojis.
Your Task: Write a PHP script that does the following:
- Define a string variable
$api_responsecontaining the following JSON:'{"product_name": "Café Espresso Machine ☕", "price": 299.99, "tags": ["kitchen", "luxury"]}'. - Decode this string into an associative array.
- Wrap the decoding process in a
try-catchblock using theJSON_THROW_ON_ERRORflag to handle any potentialJsonException. - Once decoded, use
json_encodeto print the array back to the screen, but ensure the output is pretty-printed and the Unicode characters (like the emoji and the 'é') are not escaped.
Test your error handling by intentionally removing a quote or a bracket from the $api_response string and ensuring your catch block handles the failure gracefully.
There are no comments for now.