Home > database >  Implicit conversion from float to int loses precision when trying to access array
Implicit conversion from float to int loses precision when trying to access array

Time:05-19

So the error message here is straightforward but I cannot figure out why it is happening. Just upgraded to PHP 8 and trying to work through fixing deprecations.

I have $object which looks like this (all string keys):

Array
(
    [a] => ABC
    [b] => 599.97
    [c] => 0.00
    [d] => 50
    [e] => Test
)

I have $field and when I do var_dump($field) I get float(1.05)

In my code the following is happening: I want to check if $field is a valid key of $object. If it is, I want to use the accessed value via the key, if not, I want to use $field as the value instead.

So I have the following code:

$a = $object[$field] ?? $field;

However it is this EXACT line of code that is triggering the following warning:

DEPRECATED | PID: 6978 | CODE: 8192 | MESSAGE: Implicit conversion from float 1.05 to int loses precision

I thought maybe it has something to do with the null coalescence but this code triggers the same warning too:

$a = $object[$field];

Note that $a here is just a random stand-in unused variable that I didn't type hint or declare anywhere else, and when I use this dummy variable, the warning still occurs.

Why is this happening? How is there an implicit conversion to int happening here? It's driving me crazy trying to fix this.

CodePudding user response:

From the manual (emphasis mine)-

Additionally the following key casts will occur:

...

Floats are also cast to ints, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.

...

CodePudding user response:

In PHP array's key could be int or string. Every other type need to be converted to one of these.

When you do $object[1.05] it internally converts this value to int, so it executes $object[1], but this behaviour can be misleading, so since PHP 8.1 you get warning.

  •  Tags:  
  • php
  • Related