2012年12月19日 星期三

PHP array key的自動轉型

PHP 陣列的 key 指定時可以用字串、整數、浮點數、布林值或 NULL (註:不能使用陣列和物件當 key)
但執行時 PHP 會自動轉換‏為整數和字串,規則如下
官方說明:http://php.net/manual/en/language.types.array.php
  • Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
  • Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.
  • Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.
  • Null will be cast to the empty string, i.e. the key null will actually be stored under "".
  • Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
例如
$arr = array(

"8"=>"a", //轉型為數字8

"08"=>"b", //不轉型,維持字串"08",因為"08"不是有效的十進位整數

"8.7"=>"c", //不轉型

2.6=>"d", //浮點數去掉小數點,轉型為整數2

"-3.6"=>"e", //不轉型

-4.6=>"f", //浮點數去掉小數點,轉型為整數-4

TRUE=>"g", //布林值TRUE轉型為整數1

FALSE=>"h", //布林值FALSE轉型為整數0

NULL=>"i" //NULL轉型為空字串""

);

var_dump($arr);
結果為
array(9) {

[8]=>string(1) "a"

["08"]=>string(1) "b"

["8.7"]=>string(1) "c"

[2]=>string(1) "d"

["-3.6"]=>string(1) "e"

[-4]=>string(1) "f"

[1]=>string(1) "g"

[0]=>string(1) "h"

[""]=>string(1) "i"

}

沒有留言:

張貼留言