anujgarg Posted October 8, 2009 Share Posted October 8, 2009 Hello Everyone, I was trying to run the following code: <?php $ar = array("A", 0=>"B", "0.1"=>"C", 0.2=>"D"); print_r($ar); ?> And found a strange output. I found: Array ( [0] => D [0.1] => C ) But I don't understand why it is showing the output like this. Can anyone describe the reason for the same? TIA Anuj Garg Link to comment https://forums.phpfreaks.com/topic/176961-strange-output/ Share on other sites More sharing options...
Mark Baker Posted October 8, 2009 Share Posted October 8, 2009 Array keys can only be integer or string values. Floats in key are truncated to integer. Your use of a float (0.2) is clearly causing some confusion Looking at each elemet as it's added: $ar = array("A", 0=>"B", "0.1"=>"C", 0.2=>"D"); "A" (no index) creates an entry with index 0 and value "A" 0=>"B" (integer index) overwrites the existing entry with index 0 and value "A", replacing it with value "B" "0.1"=>"C" (string index) creates an entry with index "0.1" and value "C" 0.2=>"D" (float index) truncates the float index to 0 then overwrites the existing entry with index 0 and value "B", replacing it with value "D" Link to comment https://forums.phpfreaks.com/topic/176961-strange-output/#findComment-933072 Share on other sites More sharing options...
anujgarg Posted October 8, 2009 Author Share Posted October 8, 2009 thanks Mark for the quick reply... Link to comment https://forums.phpfreaks.com/topic/176961-strange-output/#findComment-933107 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.