PHP - How to check array key exists when key include decimal place?

443 Views Asked by At

I was wondering whether it would be okay for some assistance in understanding why array_key_exists doesn't find my key when it's using decimal places?

<?php
$arr[1] = 'test';
$arr[1.1] = 'anothertesty';

foreach ($arr as $key => $value) {
    if (array_key_exists($key, $arr)) {
        echo 'found' . $key;
    }
}

Can anybody please advise what's the correct way of working with this. I need the 1.1 array key to be found.

2

There are 2 best solutions below

0
On BEST ANSWER

You can use strings as keys, so you won't have float to int conversion. When necessary to compare, you can convert it back to float:

<?php
$arr['1'] = 'test';
$arr['1.1'] = 'anothertesty';

foreach ($arr as $key => $value) {
    if (array_key_exists($key, $arr)) {
        echo 'found' . $key;
    }
}
1
On

If u use a float as key, it will be automatically casted to an int

Look at the following documentation

https://www.php.net/manual/en/language.types.array.php

The key can either be an int or a string. The value can be of any type.

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.

Means, your float is casted to int and

$arr[1.1] = 'test';

is now accessible via

echo $arr[1]

Additionally in your case the first assignment

$arr[1] = 'test';

will be immediately overwritten with anothertesty by calling

$arr[1.1] = 'anothertesty';

Thats why in the end you will just find 1 as the only key in your array