Here’s another short post detailing some odd behavior in PHP.

Let’s have a look at the following simple piece of code:

$arr = array(
  1 => 'Hello',
  1.5 =>'World',
  true=>"!"
);
var_dump($arr);

What would the output of this be? Surprisingly this does the following:

array(1) {
  [1]=>
  string(1) "!"
}

So what is causing this? First off all array keys in PHP must either be a string or an int.

1 is a valid key so the first key and value goes in without incident. 1.5 however is not a string or an int and so is an invalid key. In this case it is converted to an integer 1. Since 1 has already been used the previous value is overwritten The final key is a boolean so it is also similarly converted to an int 1 which again overwrites the key leaving a single value in the array.

See the Puzzlers tag for other posts in this series.