Prerequisites and identifier policy

External record identifiers often look numeric even though the application never adds or divides them. Treating such an identifier as a floating-point number can lose digits. This PHP 8 example decodes JSON with JSON_BIGINT_AS_STRING and normalizes accepted identifiers to strings. The fixture was executed on PHP 8.3.6 with the standard JSON extension; no packages or database are required.

The application contract is a nonnegative sequence of decimal digits with no leading zero except the single identifier zero. This is a policy for record IDs, not a general numeric parser. If your upstream system defines identifiers with leading zeros, preserve those as strings and change the validator deliberately. Do not accidentally collapse distinct identifiers while cleaning input.

Decode before validating the field

json_decode receives its options as the fourth argument. The depth argument is explicitly 32, and malformed JSON raises JsonException through JSON_THROW_ON_ERROR. JSON_BIGINT_AS_STRING preserves integer tokens that exceed the platform integer range. Values that fit may still decode as integers, so the function handles both integers and strings before returning one consistent string type.

The root must be a JSON object with an id property. Decoding into stdClass keeps an object distinct from a JSON array. A present null value still fails the field validation. Small integer tokens are converted to strings only after checking that they are nonnegative. String values must match the full canonical digit pattern.

Why floating-point input is rejected

The fixtures reject 1.0 and 1e3 even though each may describe an integral mathematical value. They arrive through the floating-point path, which cannot establish that arbitrary original identifier digits were preserved. Converting a decoded float back to a string cannot recover information already lost. Request a digit-string identifier upstream when you control the wire contract.

The output encoder emits the normalized ID as a JSON string. Keep that representation when passing it to JavaScript or another consumer with a different integer range. Avoid JSON_NUMERIC_CHECK for identifier payloads because turning a digit string back into a number defeats the output contract. Use exact string comparisons for identity rather than arithmetic comparisons.

Edge cases and troubleshooting

The tests cover a small integer, zero, a token larger than a signed 64-bit maximum and the equivalent quoted string. Nine negative fixtures cover float syntax, exponent syntax, negative values, booleans, null, leading zeros, missing IDs, an array root and broken JSON. RuntimeException-based checks remain active even when PHP assertions are disabled.

PHP integer size depends on the platform. The executed host was 64-bit; a 32-bit PHP runtime was not tested. The function is designed to accept either the integer or preserved-string path, but that design should be verified on any additional deployment architecture. Also bound HTTP body size before decoding real requests; the depth limit alone does not bound payload bytes or identifier length.

Complete example

Save as ids.php.

<?php
declare(strict_types=1);
function recordId(string $json): string {
    $row = json_decode($json, false, 32,
        JSON_BIGINT_AS_STRING | JSON_THROW_ON_ERROR);
    if (!$row instanceof stdClass || !property_exists($row, 'id')) {
        throw new InvalidArgumentException('missing record id');
    }
    $id = $row->id;
    if (is_int($id) && $id >= 0) {
        return (string) $id;
    }
    if (is_string($id) && preg_match('/\A(?:0|[1-9][0-9]*)\z/', $id) === 1) {
        return $id;
    }
    throw new InvalidArgumentException('id must be nonnegative decimal digits');
}
function check(bool $ok): void {
    if (!$ok) throw new RuntimeException('check failed');
}
check(recordId('{"id":9}') === '9');
$id = recordId('{"id":9223372036854775808}');
check($id === '9223372036854775808');
check(recordId('{"id":"9223372036854775808"}') === $id);
check(recordId('{"id":0}') === '0');
$bad = ['{"id":1.0}', '{"id":1e3}', '{"id":-1}', '{"id":true}',
        '{"id":null}', '{"id":"09"}', '{}', '[]', '{'];
foreach ($bad as $json) {
    try {
        recordId($json);
    } catch (JsonException | InvalidArgumentException $error) {
        continue;
    }
    throw new RuntimeException('invalid id accepted');
}
echo json_encode(['id' => $id], JSON_THROW_ON_ERROR), PHP_EOL;
echo 'rejected=', count($bad), PHP_EOL;

Run and expected output

php ids.php
{"id":"9223372036854775808"}
rejected=9

Primary references

Continue with PHP tutorials.