phparrayskeyarray-key-exists

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


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.


Solution

  • 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;
        }
    }