數組用途
- array
- list/vector
- hash table
- dictionary
- collection
- queue
- stack
- tree
- multidimensional array
PHP數組本質
- hash table
數組定義
- 注意
- The comma after the last array element is optional and can be omitted.格式約束
- As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].格式約束
- The key can either be an integer or a string. The value can be of any type. key如果採用別的類型的話會發生類型轉換或報warning,避免這種情況出現
- If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.數據覆蓋
- PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays.key 類型是可以混合使用的
- The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.key的值是默認以最大一個有效int類型的key標準增加的
-
# array
$array = ("Monday",
"Tursday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",);
# dictionary
$person = array(
"id" => 12345,
"name" => "chenxilin",
"age" => 25,);
數組引用
- [key] 或 {key} 多維數組可多個
- As of PHP 5.4 it is possible to array dereference the result of a function or method call directly.
- As of PHP 5.5 it is possible to array dereference an array literal.
- 注意:
- 特殊賦值:arr[] = value,用於追加value值到數組中,key採用數組中最大一個有效int類型的key增加;
- 如果該數組arr不存在或原來不是數組時,這會被創建一個新的數組出來並添加元素。
數組修改、刪除
- To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.使用unset方法,可以刪除整個數組或其中某個key/value
數組遍歷
foreach ($arr as $key => $value ) {
// do something for $key and $value;
}
有用的方法
- array_value($arr) 返回一個re-index的數組,使得key中int類型是從0開始連續增長的而不會斷開。
- count($arr) 獲得數組長度
- sort($arr) … 數組排序算法
迭代器接口實現foreach
實現構造方法和以下接口
1. Iterator::current — Return the current element
2. Iterator::key — Return the key of the current element
3. Iterator::next — Move forward to next element
4. Iterator::rewind — Rewind the Iterator to the first element
5. Iterator::valid — Checks if current position is valid