Skip to content
PHP Logo

How can PHP developers ensure that JSON strings generated from PHP functions contain the correct data types, such as numbers instead of strings?

When generating JSON strings from PHP functions, developers can ensure that the correct data types are included by explicitly casting variables to the desired data type before encoding them into JSON. This can be achieved by using type casting functions like (int), (float), or (bool) to ensure that numbers are encoded as numbers in the JSON string.

php
$data = [
    'integer' => (int) $integerValue,
    'float' => (float) $floatValue,
    'boolean' => (bool) $booleanValue
];

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