手冊
H1 class=sect1>
在PHP中一個數組實際上是一個有次序的映射。一個映射是映射值到關鍵字上。這個類型在單獨的方法上被最佳化的,你可以作為一個真實的數組或一個列表(向量),hashtable (一個映射的執行),字典,聚集,堆棧,隊列和更多的來使用它。因為你可能還有另外的PHP-數組作為一個值,你也可以十分容易的模仿樹結構。
這個結構的解釋超過了這本手冊的範圍,但是你將發現為這結構的最小的範例。關於這個結構的更多資訊,請你查閱其它文獻。
array()指定數組
一個數組可以被array() 構造。它由一對key => value並用逗號分割的一系列的號碼組成。
一個 key 是任意的非負整數或一個字串組成。 如果一個是由一個標準的非負整數表達的,它將被解釋成這樣(i.e. '8' 將被解釋成8,'08' 將被解釋成'08').
一個值可以是任意的。
忽略鍵。如果你忽略一個鍵,那麼新鍵將用最大的整數索引加一。如果整數索引也不存在,這個鍵將是0。如果你已經指定一個值給一個鍵,那麼這個將被複蓋。
array( [key =>] value
, ...
)
// 鍵是任意的字串或非負整數
// 值可以是任意的
你可以通過明確的設定值去修改一個已存在的數組。
可以用帶方括弧的鍵去分配值給數組。你也可以忽略這個鍵,在變數名後加一對空方括弧。 $arr[key] = value;
$arr[] = value;
// key 是任一字元串或非負整數
// value 可以是任意的
如果$arr 不存在,它將被建立。如此也可能選擇性的去指定一個數組。去改變一個確定的值,剛好分配一個新值給它。如果你想去刪除一對鍵/值,你需要用 unset() 。
為數組的工作,有一睦有用的函數,參見數組函數 段落。
foreach 流程式控制制明確提供了一個容易的方法去迴圈一個數組。
在舊的指令碼中你可能看到過下邊的文法:
$foo[bar] = 'enemy';
echo $foo[bar];
// etc
這是錯誤的,但它會工作。然而,為什麼是錯誤的呢?在這之後的syntax 片段中規定,運算式必須在方括弧之間。。這意味著你可以象下邊一樣做:
echo $arr[ foo(true) ];
這個例子使用一個函數的傳回值作為數組的索引。PHP也知道是常量,你可以見E_*。
$error_descriptions[E_ERROR] = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE] = "This is just an informal notice";
注意,E_ERROR 是個有效標識符,剛好象第一個例子中的bar 。But the last example is in fact the same as writing:
$error_descriptions[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
because E_ERROR equals 1, etc.
Then, how is it possible that $foo[bar] works? It works, because bar is due to its syntax expected to be a constant expression. However, in this case no constant with the name bar exists. PHP now assumes that you meant bar literally, as the string "bar", but that you forgot to write the quotes.
At some point in the future, the PHP team might want to add another constant or keyword, and then you get in trouble. For example, you already cannot use the words empty and default this way, since they are special keywords.
And, if these arguments don't help: this syntax is simply deprecated, and it might stop working some day.
Tip: When you turn error_reporting to E_ALL, you will see that PHP generates warnings whenever this construct is used. This is also valid for other deprecated 'features'. (put the line error_reporting(E_ALL); in your script)
Note: Inside a double-quoted string, an other syntax is valid. See variable parsing in strings for more details.
The array type in PHP is very versatile, so here will be some examples to show you the full power of arrays.
// this
$a = array( 'color' => 'red'
, 'taste' => 'sweet'
, 'shape' => 'round'
, 'name' => 'apple'
, 4 // key will be 0
);
// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // key will be 0
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array( 0 => 'a' , 1 => 'b' , 2 => 'c' ),
// or simply array('a', 'b', 'c')
Example 6-4. Using array()
// Array as (property-)map
$map = array( 'version' => 4
, 'OS' => 'Linux'
, 'lang' => 'english'
, 'short_tags' => true
);
// strictly numerical keys
$array = array( 7
, 8
, 0
, 156
, -10
);
// this is the same as array( 0 => 7, 1 => 8, ...)
$switching = array( 10 // key = 0
, 5 => 6
, 3 => 7
, 'a' => 4
, 11 // key = 6 (maximum of integer-indices was 5)
, '8' => 2 // key = 8 (integer!)
, '02' => 77 // key = '02'
, 0 => 12 // the value 10 will be overwritten by 12
);
// empty array
$empty = array();
Example 6-5. Collection
$colors = array('red','blue','green','yellow');
foreach ( $colors as $color ) {
echo "Do you like $color?\n";
}
/* output:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
*/
Note that it is currently not possible to change the values of the array directly in such a loop. A workaround is the following:
Example 6-6. Collection
foreach ( $colors as $key => $color ) {
// won't work:
//$color = strtoupper($color);
//works:
$colors[$key] = strtoupper($color);
}
print_r($colors);
/* output:
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => YELLOW
)
*/
This example creates a one-based array.
Example 6-7. One-based index
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
/* output:
Array
(
[1] => 'January'
[2] => 'February'
[3] => 'March'
)
*/
Example 6-8. Filling real array
// fill an array with all items from a directory
$handle = opendir('.');
while ($file = readdir($handle))
{
$files[] = $file;
}
closedir($handle);
Arrays are ordered. You can also change the order using various sorting-functions. See array-functions for more information.
Example 6-9. Sorting array
sort($files);
print_r($files);
Because the value of an array can be everything, it can also be another array. This way you can make recursive and multi-dimensional arrays.
Example 6-10. Recursive and multi-dimensional arrays
$fruits = array ( "fruits" => array ( "a" => "orange"
, "b" => "banana"
, "c" => "apple"
)
, "numbers" => array ( 1
, 2
, 3
, 4
, 5
, 6
)
, "holes" => array ( "first"
, 5 => "second"
, "third"
)
);