Search code examples
phpleading-zero

Return string with leading zeros in PHP


Similar to this unsolved question

My PHP output requires JSON_NUMERIC_CHECK enabled, however there is one string nick column in my database that needs to be returned originally as a string. Values in that column can contain numbers and there's no length restriction. Code example:

$response["players"] = array();
...
$stmt = $connection->prepare('SELECT id, nick FROM players WHERE NOT id = ? ORDER BY nick');
$stmt->bind_param('i', $_POST["id"]);
$stmt->execute();
$result = $stmt->bind_result($id, $nick);
while ($stmt->fetch()) {
    $players = array();
    $players["id"] = $id;
    $players["nick"] = $nick;
    array_push($response["players"], $players);
}
...
echo json_encode($response, JSON_NUMERIC_CHECK);

For example, nick "007" is being returned as "7" and I need it to be the original "007". Removing "JSON_NUMERIC_CHECK" helps, but it bugs the rest of the code. Strval() function used like quoted below didn't help.

$result = $stmt->bind_result($id, strval($nick));
$players["nick"] = strval($nick);

Solution

  • In PHP there is unfortunately no explicit type for variables, this makes your problem not so easy to solve.

    I came with 2 solution.

    1) if you like OOP, make a Serializable, Arrayable class to use as container for your string with a method returning the right encoded value.

    2) first encode using JSON_NUMERIC_CHECK in order to make sure your data is what you expect it is, then decode the validated data, manually set the string to its origina value, then encode again but this time not using JSON_NUMERIC_CHECK.

    $str = $response['nick'];
    $response = json_decode(json_encode( $response, JSON_NUMERIC_CHECK ) );
    $response->nick = $str;
    $response = json_encode( $response );