I have few rest API’s which are written in core PHP. I am using this API’s for IOS mobile application. But sometimes in the response, few variables are getting converted as Int to string data type. Which is stopping the execution of the application. When I print the response using print_r() the values coming out correctly, but when I echo the response using json_encode(), few int values are printing as string.
This issue is not happening all the time only sometimes I am mfacing this issue.
$stmt = $pdo->prepare('SELECT * From Table');
$stmt->execute(['value' => $_POST['value']]);
$rowvalue = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rowvalue as $type => $value) {
if ($value === null) {
$rowvalue[$type] = "";
}
if ($rowvalue["isotherfacilitycompatible"] === "") {
$rowvalue["isotherfacilitycompatible"] = 0;
}
if ($rowvalue["serviceablevendor"] === "") {
$rowvalue["serviceablevendor"] = "";
}
if($type == 'rmacreatedid'){
$rowvalue[$type] = (int)$rowvalue[$type];
}
}
$response["details"][$type] = $rowvalue[$type];
}
echo json_encode($response);
Can anyone give me any idea, what may be causing this issue.
2
Answers
You can use
json_encode()
withJSON_NUMERIC_CHECK
flag:Note that since PHP 5.3.3, there’s a flag for auto-converting numbers (the options parameter was added in PHP 5.3.0):