PHP json_encode encoding numbers as strings

PHP json_encode encoding numbers as strings

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP json_encode Encoding Numbers as Strings

When working with APIs in a Laravel ecosystem, you might encounter a scenario where json_encode seems to be behaving unexpectedly by converting integer values into strings within your JSON output. This often happens when debugging an issue where JavaScript receives data like "id": "3" instead of "id": 3. If your backend logic expects numeric types for calculations or comparisons, receiving a string can break those operations immediately.

The root cause is rarely a bug in the json_encode function itself. Instead, it usually stems from how PHP stores the variable before serialization. In PHP, data types are dynamic, but once a value is wrapped in quotes (making it a string) or cast to a string during an operation like array indexing, that type change is permanent until explicitly corrected.

Consider this common pattern where developers mistakenly use string keys for associative arrays:

$data = ['id' => "3"]; 
echo json_encode($data);
// Output: {"id":"3"}

Here, the value "3" is already a string. json_encode faithfully represents the PHP data type in the JSON output. It does not automatically convert strings back to numbers unless you intervene beforehand. Even if you intended to store an integer, accidentally assigning a string literal or concatenating a number with a string can result in this behavior:

$id = 3;
$userId = $id . "0"; // Result is now the string "30"
$data = ['id' => $userId]; 
echo json_encode($data); 
// Output: {"id":"30"}

To prevent json_encode from outputting numbers as strings, you must ensure that the values in your array are genuine PHP integers or floats at the moment of serialization. The most robust approach is to perform type casting or validation before passing the data to the encoder.

$data = [
    'id' => (int) "3", // Cast string to int
    'count' => 5,      // Already an int
];

echo json_encode($data);
// Output: {"id":3,"count":5}

This works because json_encode will output a number without quotes if the PHP value is of type int or float. However, be wary of floating-point precision issues. While json_encode handles floats well, extremely large numbers might lose precision depending on your JSON decoder's configuration in JavaScript.

Another frequent pitfall involves array keys. In PHP 7.4 and earlier, if you define an array with string keys that look like numbers (e.g., '0' or '1'), those keys remain strings. You must explicitly cast the key itself if you require numeric indices:

// Keys are strings here
$data = ['3' => 'value']; 
echo json_encode($data); 
// Output: {"3":"value"}

// Force numeric index
$data2 = [3 => 'value']; 
echo json_encode($data2); 
// Output: ["value"] (numeric key)

If you are building a response for an API, always verify the types of your data structures. Using tools like var_dump or gettype() during development can quickly reveal if a value has been inadvertently converted to a string. For instance, checking is_numeric($id) is not sufficient because it returns true for both "3" and 3. You must use is_int() or is_float() to ensure the strict type required by json_encode.

In larger applications using Laravel, this issue often surfaces when merging arrays from different sources where one source treats IDs as strings. You might need to sanitize your payload before returning it:

public function response()
{
    $payload = [
        'id' => (int) $this->model->id,
        'status' => 'active',
    ];

    return response()->json(json_encode($payload));
}

By ensuring that your PHP values match the JSON schema expectations before serialization, you eliminate the ambiguity at the JavaScript level. This practice ensures that numeric operations in your frontend logic function as intended without requiring complex regex workarounds or type conversions on the client side.

Our network