-1

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.

lky
  • 1,081
  • 3
  • 15
  • 31
  • 4
    _"why array_key_exists doesn't find my key when it's using decimal places?"_ - because your array does not contain what you think - which a simple `var_dump($arr);` could have shown you. And now, please go read https://www.php.net/manual/en/language.types.array.php – CBroe Aug 31 '21 at 13:46
  • 3
    Your code works https://3v4l.org/Z7LDG if you make the 1.1 into `'1.1'` – RiggsFolly Aug 31 '21 at 13:46
  • 2
    "The key can either be an int or a string. The value can be of any type. " https://www.php.net/manual/en/language.types.array.php – palindrom Aug 31 '21 at 13:47
  • Thanks @CBroe, RiggsFolly, palindrom. - All sorted now – lky Aug 31 '21 at 14:01

2 Answers2

1

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

Jim Panse
  • 2,220
  • 12
  • 34
  • Thanks for the explanation. I've resolved the issue by making the key a string of '1.1' – lky Aug 31 '21 at 14:02
1

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;
    }
}
Leandro P.
  • 26
  • 2