1

While debugging some unexpected behaviour i came across the following situation:

$value = 20000;
var_dump($value['someKey']);

Unexpectedly this did not throw an error, warning, notice or even strict warning. The same can be done with a boolean of float. It does not throw any kind of error and returns null.

Why does it allow this? For every single piece of weird behaviour in PHP I found an explaination (even though some are not really logical) but in this case i am at a loss.

Note: This question is purely out of curiosity and has no real world application.

nvanesch
  • 2,540
  • 14
  • 25
  • Php is a loosely typed language, http://wshell.wordpress.com/2009/10/08/quicky-1-php-is-loosely-typed-what-does-that-meand/ – ArtisticPhoenix Jul 08 '14 at 07:50
  • 1
    @ArtisiticPhoenix Sooo....? – deceze Jul 08 '14 at 07:50
  • @ArtisiticPhoenix I am well aware that it is loose typed. however, that does not explain this behaviour. Should it treat the integer as an array, than it should give an undefined index error, should it treat it as a string it should give a string offset error. – nvanesch Jul 08 '14 at 07:52
  • It means you can dynamically change the type of any variable at runtime, one second its an int the next a float, the next an array etc. This can be a double edged sword if you ask me. – ArtisticPhoenix Jul 08 '14 at 07:52
  • Oh, its probably casting it to an array, and . or its a result of using var_dump, does it do the same with print_r - edit works with print_r too – ArtisticPhoenix Jul 08 '14 at 07:57
  • I would expect it to be cast to array and next it would give an undefined index error. But clearly it doesn't. Same with echo, print_r, etc. Also var_dump does not suppress errors. – nvanesch Jul 08 '14 at 08:01
  • someone closed it, its casting, try (array)$value['someKey']; – ArtisticPhoenix Jul 08 '14 at 08:03
  • 1
    @deceze thank you for finding this duplicate!! The accepted answer in that post in my opinion does not fully explain it, but the second answer by stackfu shows me exactly what is happening here.. just a piece of poorly designed code ;) – nvanesch Jul 08 '14 at 08:03

0 Answers0