PHP中可以通过指定元素的键来访问数组中的元素,使用整数和变量键访问值没有问题,但是使用字符串类型的键可能就有问题了,所以一定要注意。如下面的代码:
<?php
//先定义两个数组
$breads = array("baguette", "naan", "roti", "pita");
$computer = array("processor" => "Muncheron 6000",
"memory" => 2048, "HDD1" => 80000,
"graphics" => "NTI Monster GFI q9000");
// Example 1
// 用整数键2来访问数组元素,没有问题。
//
echo "I like to eat $breads[2] every day!<br/>\n";
//
// Example 2
// 用变量键访问数组元素,也没有问题。
//
$feature = "memory";
echo "My PC has $computer[$feature]MB of memory<br/>\n";
//
// Example 3, 4
// 用字符串类型的键访问数组元素,两个都提示错误
//
echo "My PC has a $computer[\'processor\'] processor<br/>\n";
echo "My PC has a $computer["processor"] processor<br/>\n";
//
// Example 5, 6
// 将Example 3, 4改为如下就OK了,但不提倡Example 6,看了Example 7,8就明白了
//
echo "My PC has a {$computer[\'processor\']} processor<br/>\n";
echo "My PC has a $computer[processor] processor<br/>\n";
//
// Example 7,8
// 不带引号指定键名是外边应该有双引号,Example 7提示错误,Example 8正常
//
echo $computer[processor];
echo "$computer[processor]";
//
//Example 9
//引用不存在的索引,也会出问题
//
echo "My PC has a {$computer[\'soundcard\']} sound card<br/>\n";
//
//Example 10
//正确使用常量的方法
//
define(\'FFFA\',"memory");
echo "My PC has {$computer[FFFA]}MB of memory<br/>\n";
?>
基本上就这么多了,现在着重说一下Example 10,使用常量的名称和不带引号的字符串的名称相同时,也会出问题的,被使用的是常量的值。如下面代码:
<?php
$computer = array("memory" => 2048, 2=>1024);
define(\'memory\',2);
echo "My PC has $computer[memory]MB of memory<br/>\n"; //My PC has 2048MB of memory
echo "My PC has {$computer[memory]}MB of memory<br/>\n" //My PC has 1024MB of memory
?>