Jump to content

Strange Output


anujgarg

Recommended Posts

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.