0

I have this code:

  $val = (float) $desc;
  if (!isset($runepage['statistics'][$key])) {
        $runepage['statistics'][$key] = (float) 0.0;
  }
  $runepage['statistics'][$key] += $val;

where $val is a float.

But when I print out the array at the end all the values end up as integers. For example, if there were 1.5, 1.5, 1.5 for the same $key, it would print out 3 rather than 4.5.

I'm not sure why it's doing this.

Edit: here's the output of the array

[statistics] => Array
    (
        [magic penetration] => 9
        [ability power per level] => 9
        [movement speed] => 3
        [magic resist] => 9
    )
8
  • Show us the code that does the printing Commented Mar 20, 2013 at 23:31
  • I can't see any integer casting going on there. Would you add in how you are printing the array? Commented Mar 20, 2013 at 23:32
  • You don't have to do (float) 0.0 by the way - a zero here will suffice, and it will still be treated as float. Commented Mar 20, 2013 at 23:33
  • I'm printing it with print_r($runepage) and I tried var_export as well. Yeah, I didn't put (float) 0.0 initially, I just started fiddling with it to see if it would change anything - it didn't. Commented Mar 20, 2013 at 23:33
  • Ah, see @porneL's answer. Perhaps you could use a string prefix to get this to work, i.e. turn your numerically indexed array into a hash? So, keys could be key_3.5 rather than 3.5. Commented Mar 20, 2013 at 23:37

1 Answer 1

5

Sorry, I misread your question assuming the $key was a float.

In case of $val — I don't know. It should work fine for values, so source of the problem may be elsewhere. In PHP it's safe to add integers and floats together and the result will be float.


If the $key was a float:

That's normal, documented behavior. Arrays are not supposed to be indexed by floats.

Also numeric-looking strings are cast to integers too. $a[5] === $a['5'].

Unfortunately PHP arrays are not a generic key-value store. Your best bet is serializing keys to a string that does not start with a digit.

Sign up to request clarification or add additional context in comments.

4 Comments

he never said that $key vas float
@Acuao - he quite explicitly does say that in the penultimate paragraph of his question: But when I print out the array at the end all the keys end up as integers
It's the $val that's a float, the key is a string. I've added the output of the array to the initial post.
yes sure i know, you was saying that if for a key the value was 1.5 (x3) its print 3 instead of 4.5? - @mark-baker i'm not an english pro, but you're totaly wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.