skip to Main Content

I have a php code to convert an array to json:

$output = array(
    'name' => "annie",
    'is_bool' => 1,
    'total_amount' => '431.65',
    'phone_number' => '0272561313'
);
    
echo json_encode($output,JSON_NUMERIC_CHECK);

but JSON_NUMERIC_CHECK removed 0 numbers at first value.

I want this output:

{"name":"annie","is_bool":1,"total_amount":431.65,"phone_number":0272561313}

my $output initial of a query of database.

2

Answers


  1. I’m afraid there’s no way to do what you’re trying to do with a PHP number.

    The leading zero on the phone number won’t be respected if it’s cast to a float or integer. Neither will country codes, such as +44.

    Cast it as a string; it’s all you can do.
    So:

    $output = [
        //Don't mix your quote types please, it makes baby Jesus cry.
        'name' => 'annie',
        //Shouldn't this be a boolean? JSON will handle it perfectly well
        'is_bool' => 1,
        //Let's cast explicitly to float here, just-in-case
        'total_amount' => (float) 431.65,
        ///Leave this as a string
        'phone_number' => '0272561313'
    ];
    
    Login or Signup to reply.
  2. This part makes no sense:

    "phone_number":0272561313
    

    There is no point in adding leading zeros to numbers, any decent library used to parse the resulting JSON will automatically remove them, because that is how numbers work. Phone numbers are called numbers partly for historial reasons (from the era before telephone exchanges were fully automated), partly because it’s informal English.

    I suspect what you really want is to de-stringify some known numeric fields:

    array_walk(
        $output,
        static function (mixed &$value, string $key) {
            if ($key === 'total_amount' && is_string($value)) {
                $value = (float)$value;
            }
        },
    );
    
    echo json_encode($output);
    
    {"name":"annie","is_bool":1,"total_amount":431.65,"phone_number":"0272561313"}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search