How does json_encode handle null values in PHP arrays?

When using json_encode in PHP, null values in arrays are automatically converted to the JSON null value. This means that if a key in an array has a null value, it will be represented as "null" in the JSON output. To handle null values in PHP arrays when encoding them to JSON, you can explicitly check for null values and replace them with a custom value before encoding the array.

$data = [
    'key1' => 'value1',
    'key2' => null,
    'key3' => 'value3'
];

foreach ($data as $key => $value) {
    if ($value === null) {
        $data[$key] = 'custom_value';
    }
}

$json = json_encode($data);
echo $json;