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
28: Working with JSON in PHP
I've seen this happen more times than I can count: a developer gets a JSON string from an API and, because they need to change one single value, they try to use str_replace() or preg_replace() to swap out a value directly in the string. It seems faster, right? Why bother decoding the whole thing if you just want to change "status": "pending" to "status": "complete"?
Stop treating JSON as a string
Let me show you why that approach is a disaster waiting to happen. Imagine you have a JSON string representing a user profile:
$json = '{"username": "dark_knight", "theme": "dark", "status": "active"}';
// The "clever" way to change the theme to light
$json = str_replace("dark", "light", $json);
echo $json;
// Result: {"username": "light_knight", "theme": "light", "status": "active"}
Oops. You didn't just change the theme; you accidentally renamed the user to "light_knight". This is why treating JSON as raw text is a cardinal sin in software engineering. JSON is a data format, not just a string. To work with it safely, you have to move the data from the "JSON world" into the "PHP world," make your changes, and then ship it back.
The Decode-Modify-Encode Cycle
The correct workflow is a three-step cycle. First, we use json_decode() to turn that string into something PHP actually understands—either an object or an associative array. Then we change the data using standard PHP syntax. Finally, we use json_encode() to turn it back into a string for storage or transmission.
There's one detail here that trips people up: the second argument of json_decode(). By default, it returns an object of the stdClass type. But in my experience, most PHP developers find associative arrays much easier to manipulate.
$json = '{"username": "dark_knight", "theme": "dark", "status": "active"}';
// Pass 'true' as the second argument to get an associative array
$data = json_decode($json, true);
// Now we can safely target only the 'theme' key
$data['theme'] = 'light';
// Convert it back to a JSON string
$updatedJson = json_encode($data);
If you omit that true, you'd have to use object notation ($data->theme = 'light';). Both work, but be consistent. Mixing them in one project is a recipe for "Undefined property" errors that will waste your entire afternoon.
Handling API Errors and Nulls
In a perfect world, every API sends back valid JSON. In the real world, APIs crash, return HTML error pages instead of JSON, or send back empty strings. If json_decode() fails, it returns null.
I highly recommend checking the result before you try to access any keys. If you try to treat null as an array, PHP will throw a warning. I usually wrap my decoding in a simple check or use json_last_error() if I need to know exactly why the parsing failed (like a trailing comma that shouldn't be there).
$json = '{"invalid": json}'; // This is malformed JSON
$data = json_decode($json, true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
// Log the error or tell the user the API is acting up
die("JSON Error: " . json_last_error_msg());
}
One last pro tip: when encoding data to send to a browser or another API, use the JSON_PRETTY_PRINT flag. It doesn't change the data, but it adds whitespace and line breaks, making it actually readable for humans when you're debugging in the browser network tab.
echo json_encode($data, JSON_PRETTY_PRINT);📋 Practical Task
The Game Inventory Sync System
You are building a synchronization tool for a multiplayer game. You receive a JSON string representing a player's inventory, but you need to update it based on a recent loot drop before saving it back to the database.
Your Task:
- Start with this JSON string:
'{"player": "Zeldar", "level": 12, "inventory": {"potions": 3, "arrows": 50, "gold": 120}}' - Decode the string into a PHP associative array.
- Add 2 to the
potionscount. - Add a new item to the inventory:
"magic_scroll"with a value of 1. - Increase the
levelby 1. - Encode the modified array back into a JSON string using
JSON_PRETTY_PRINTand echo the result.
Note: Ensure you are using the associative array approach (the second parameter of json_decode) to handle the nested inventory data.
There are no comments for now.