Home > Software design >  API response is automatedly getting converted from int to string
API response is automatedly getting converted from int to string

Time:12-29

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.

CodePudding user response:

json_encode with JSON_NUMERIC_CHECK 

    $result = array(
        'is_bool' => true,
        'user_id' => 121,
        'total_amount' => '431.65',
        'phone_number' => '9090909000'
    );
    echo json_encode($result,JSON_NUMERIC_CHECK);

CodePudding user response:

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):

$arr = array( 'row_id' => '10', 'name' => 'John' );
echo json_encode( $arr, JSON_NUMERIC_CHECK ); // {"row_id":10,"name":"John"}
  • Related