DasSaffe
DasSaffe

Reputation: 2198

var_dump on interactive mode shows unexpected result

I'm on my shell (ubuntu 12) and encountered a strange behaviour, which I can't explain:

var_dump(array(1.5 => "a", 2.2 => "b", 2.5 => "c"));

prints the following in my shell:

array(2) {
    [1]=>
    string(1) "a"
    [2]=>
    string(1) "c"
}

can someone please explain this? What happens to "b"? Why is it not printed? (PHP 5.3)

Upvotes: 0

Views: 114

Answers (2)

jszobody
jszobody

Reputation: 28911

Two things going on here:

  1. Array keys can only be strings or integers. Floats will be cast to integers.
  2. If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

So your 2.2 and 2.5 keys were cast to the integer 2. The second one overwrote the first one.

http://php.net/manual/en/language.types.array.php#example-99


One option would be to use string keys:

var_dump(array("1.5" => "a", "2.2" => "b", "2.5" => "c"));

array(3) {
  '1.5' =>
  string(1) "a"
  '2.2' =>
  string(1) "b"
  '2.5' =>
  string(1) "c"
}

Upvotes: 6

Nana Partykar
Nana Partykar

Reputation: 10548

Type Casting and Overwriting example

<?php
$array = array(
    1    => "a",
    2.2  => "b",
    2.5  => "c",
);
var_dump($array);
?>

The above example will output:

array(2) {
    [1]=>
    string(1) "a"
    [2]=>
    string(1) "c"
}

As in the above example 2.2 & 2.5 are cast to 2, the value will be overwritten on every new element and the last assigned value "c" is the only one left over.

For more info, please click Type Casting and Overwriting example

Upvotes: 0

Related Questions