4

This function

function convert($size) {
  $unit = array(
    'B',
    'KByte',
    'MByte',
    'GByte',
  );
  return round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
}

works but PHPStorm says

 Illegal array key type on line 54

that means $unit[$i].

What's wrong with this function?

4
  • 3
    First guess - PHPStorm sees that floor returns a float, and using a float as an array key is usually a no-no. Be advised that some other functions, like array_key_exists, will actually produce a runtime error if you pass that $i as the key, based solely on its type. Commented Nov 16, 2013 at 14:41
  • Where did you define $i? Commented Nov 16, 2013 at 14:42
  • @putvande ($i = floor(... Commented Nov 16, 2013 at 14:43
  • Ow yeah.. Missed that. Commented Nov 16, 2013 at 14:43

1 Answer 1

4

floor returns a float, not an integer. (Counter-intuitive, but true.) Floats are illegal keys in PHP arrays.

The code works fine, because floats are implicitly cast to integers when used as keys in an array, but I imagine that is why you are getting the notification in PHPStorm.

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

1 Comment

I fixed it now with $unit[(int)$i] and the notification is gone.

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.