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

abkrim's avatar
Level 13

Strange behavior when converting from an API

I have a problem calling an external API, Sendgrid, to validate email addresses.

The API client based on an (official) Sendgrid library for PHP, returns an element of the response with a float value

..."score" => 0.71214, "other_key" => "Some value"...

When I do json_decode($reponse->body(), true) (also same problem without conver to associative array) I get on array

"score" => 0.71214,0",
"other_key" => "Some value"

I have searched for a solution or information as to why this behavior, and I can't find anything.

Edit

After working with around the problem, because when try work with array an foreach() get a refactor of problem.

The problem arose when I was making a helper for a question in my application, and when doing the tests, it jumped.

public static function normalizeArray(array $array): array
{
    $new = [];

    foreach ($array as $key => $value) {
        $keys = [];
        if (($key == $value) && ($key == 0)) continue; // Solution to problem
        $newkey = str_replace('#', '_', str_replace('_', '.', str_replace('__', '#', $key)));
        $new[$newkey] = $value;
    }

    return Arr::undot($new);
}

Test function

/** @test */
function underscored_array_is_converted_on_normal_array()
{
    $array = [
        "key1" => "value1",
        "key2" => "value2",
        "key3" => 0.9998,0,
        "upperkey1_subkey1_final__one__element" => true,
        "upperkey1_subkey1_final__two__element" => false,
        "key4" => "1.1.1.1",
    ];

    $result = General::normalizeArray($array);

    ....
}

Result get same value, 0.9998,0 Which makes me think that it is a problem that I must take into account for any question that has to do with the value of the floating number. Something I don't understand.

0 likes
1 reply

Please or to participate in this conversation.