Are the lines in the keys integer?

I wrote an array for all months of the year as follows:

$MNTH["01"] = "January"; $MNTH["02"] = "February"; $MNTH["03"] = "March"; $MNTH["04"] = "April"; $MNTH["05"] = "May"; $MNTH["06"] = "June"; $MNTH["07"] = "July"; $MNTH["08"] = "August"; $MNTH["09"] = "September"; $MNTH["10"] = "October"; $MNTH["11"] = "November"; $MNTH["12"] = "December"; 

When I do a dump variable on the $MNTH keys with var_dump(array_keys($MNTH)) , I get:

 array(12) { [0]=> string(2) "01" [1]=> string(2) "02" [2]=> string(2) "03" [3]=> string(2) "04" [4]=> string(2) "05" [5]=> string(2) "06" [6]=> string(2) "07" [7]=> string(2) "08" [8]=> string(2) "09" [9]=> int(10) [10]=> int(11) [11]=> int(12) } 

I was expecting strings for the last three keys. How did he become whole? What should I do to fix this?

+4
source share
3 answers

PHP converts numeric keys to integers when creating an array element. These are not array_keys . But there is a hack for getting string numeric keys:

 $a = new stdClass; $a->{"0"} = "zero"; $a = (array) $a; var_dump($a); 

Output:

 array(1) { ["0"]=> string(4) "zero" } 

But you will not be able to access this key by index, so it is not very useful.

If you must have string keys, you will need to prefix them with another non-numeric (or null) character:

 $MNTH["001"] = "January"; $MNTH["012"] = "December"; 

From the documentation :

The key can be an integer or a string. If the key is a standard representation of an integer, it will be interpreted as such (i.e., "8" will be interpreted as 8, and "08" will be interpreted as "08"). The floats in the key are truncated to the whole. Indexed and associative array types are the same type in PHP, which can contain both integer and string indexes.

+6
source

PHP determines the type of variable based on context, so 10,11,12 is considered integer. If you want to make them be a string, you can either draw it like this.

 $MNTH[(string)"11"] = "November"; 

or concatenate an empty string.

 $MNTH["11".""] = "November"; 
0
source

Why don't you just create an associative array?

 $MNTH = array( array("01" => "January"),array("02"=>"February"),array("03"=>"March"), ... snip ... array("12"=>"December") ); 
0
source

All Articles