Forum Moderators: coopster
<?php
// What could possibly go wrong?
$test_array = array(
"3" => "three",
"3.5" => "three and a half",
"4" => "four"
);
$numeric_key = 3.5;
echo($test_array[$numeric_key]); // wrong
echo '<br>';
$string_key = "3.5";
echo($test_array[$string_key]); //right
echo '<br>';
$numeric_key = 3.5;
echo($test_array[(string) $numeric_key]); //right :)
?>
Well, at least I had the opportunity to learn that typecasting can be done right inside of the array key brackets. :)
::goes off to add (string) all over the place::
$test_array = array(
"3" => "three",
"3.5" => "three and a half",
"4" => "four"
);
This array has three entries. You have assigned your own string keys, which means there are no numeric keys in the array.
$numeric_key = 3.5;
echo($test_array[$numeric_key]); // wrong
This will of course error. You are trying to get an entry with an index of 3.5 which doesn't exist as you defined your own string indexes, and as far as I am aware, you can only have integer numeric indexes, although I may be wrong on that one.
$string_key = "3.5";
echo($test_array[$string_key]); //right
$numeric_key = 3.5;
echo($test_array[(string) $numeric_key]); //right :)
Obvisouly this works as it is getting the string index of "3.5" which you set and the second one is converting your numeric 3.5 to a string "3.5" and is making it work.
To use the array with numeric indexes, you can convert the array,
$numeric_array = array_values ($test_array);
This will give,
$numeric_array = array(
0 => "three",
1 => "three and a half",
2 => "four"
);
$numeric_key = 3.5;
echo($test_array[$numeric_key]); // wrongThis will of course error. You are trying to get an entry with an index of 3.5 which doesn't exist as you defined your own string indexes, and as far as I am aware, you can only have integer numeric indexes, although I may be wrong on that one.
Yup, what caught me by surprise is that PHP just silently converts the float value to an int value. I wasn't expecting that behavior -- I would have preferred it to return null or false with a "undefined index" notice.