Forum Moderators: coopster

Message Too Old, No Replies

Numeric keys are rounded down?

Frustrating

         

whoisgregg

8:07 pm on Jul 18, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<?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::

derek mcgilvray

8:43 pm on Jul 18, 2006 (gmt 0)

10+ Year Member



I'm just a learner, but you may have to use 'float' instead of 'int' when you set up your tables - not sure if this will help,

Derek

Sekka

9:36 pm on Jul 18, 2006 (gmt 0)

10+ Year Member



Ok, you are creating an array,

$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"
);

whoisgregg

9:42 pm on Jul 18, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld, Derek. :)

You are right about using float in a database for numbers with decimal places. In this sample code (and in my project where I discovered this "feature"), it's just a static array. :)

whoisgregg

9:46 pm on Jul 18, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$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.

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.