What is the best practice for preparing and encoding arrays in PHP for JSON responses?

When preparing and encoding arrays in PHP for JSON responses, it is best practice to ensure that the data is properly formatted and escaped to prevent any potential issues with the JSON encoding process. This can be achieved by using the json_encode() function in PHP, which will encode the array into a JSON formatted string. Additionally, it is important to set the appropriate headers to indicate that the response is in JSON format.

// Sample array data
$data = array(
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'johndoe@example.com'
);

// Encode the array into JSON format
$json_data = json_encode($data);

// Set the appropriate headers for JSON response
header('Content-Type: application/json');

// Output the JSON data
echo $json_data;