Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

princeoo7's avatar

Why and int variable is return sometimes as string in json format in api ?

I am using below code to get status output :

if (! function_exists('status')) {
    function status($code) {
        $record  =  Status::getInstance(intval($code));
        return [
            'code' => $code,
            'value' => $record->description,
        ];
    }
}

output:

"status": {
                "code": 2,
                "value": "Active"
            }

but sometimes i get output as:

"status": {
            "code": "2",
            "value": "Active"
        }

if you see the code value in both the output, one is int as originally intended. Second one is a String value. Why is this happening ? how to stop this?

0 likes
8 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Cast it as int

return [
            'code' => (int) $code,
            'value' => $record->description,
        ];
Sinnbeck's avatar

@princeoo7 to use the anwer by @automica you need to return the code on the Status model then

$record  =  Status::getInstance(intval($code));
        return [
            'code' => $record->code,
            'value' => $record->description,
        ];
1 like
princeoo7's avatar

@sinnbeck I was using this only but was thinking if their might be something else so for link from the model and the model answer is also below. its bad that we cannot have multiple answers and answer... :/

princeoo7's avatar

@automica yes this can be used as in the models. my question was regarding a custom function where I am using (int) as of now. but this is also an answer for me.

Please or to participate in this conversation.