php - Associative Array Key Casting Float String

662

In my code, I have generated an associative array with keys as floats, however the PHP documentation states that when they become key's in the array they are SUPPOSED to be cast to integers. Instead, they are being cast to strings (which is actually better for me so I'm not complaining).

The problem is that when I try to access these keys using a float as the key value, it casts only the floats with .5 to integers and creates a new entry in the array. Seems like peculiar behavior.

Example:

var_dump( $array );

Output:

array(9) {
[0] =>
int(0)
[1.25] =>
int(0)
[2.5] =>
int(0)
....}

When I try to access the value 2.5 like so,

array[2.5]++;

a new entry in the array is made atarray[2] However if I try to access the array atarray[1.25]++; I successfully add 1 to the value at key: 1.25

Any ideas?

446

Answer

Solution:

I would just stick with strings all the time:

$a = array(
    '0' => 0,
    '1.25' => 0,
    '2.5' => 0
);

$a['2.5']++;
echo $a['2.5'] . "\n";
var_dump($a);

Output is:

1
array(3) {
  [0]=>
  int(0)
  ["1.25"]=>
  int(0)
  ["2.5"]=>
  int(1)
}

People are also looking for solutions to the problem: php - MySQL No database selected

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.