How can JSON encoding and decoding be utilized effectively in PHP to store and retrieve complex data structures like arrays?

To store and retrieve complex data structures like arrays in PHP, JSON encoding and decoding can be utilized effectively. By encoding the array into a JSON string, it can be easily stored in a file or database. When needed, the JSON string can be decoded back into an array for use in the PHP script.

// Sample array to be encoded
$data = array(
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'johndoe@example.com',
    'hobbies' => array('reading', 'hiking', 'coding')
);

// Encode the array into a JSON string
$jsonString = json_encode($data);

// Store the JSON string in a file or database

// Retrieve the JSON string from the file or database
// Decode the JSON string back into an array
$decodedData = json_decode($jsonString, true);

// Access the decoded array elements
echo $decodedData['name']; // John Doe
echo $decodedData['hobbies'][0]; // reading