今天突然碰到了php的問題,發(fā)現(xiàn)這篇文章,很老的文章了,但很實用,下一篇我將整理更新的php5的數(shù)組
PHP4.0中共有超過30個新的數(shù)組相關函數(shù)。其中很多通用函數(shù)允許你檢查給定數(shù)組中是否存在特定對象、對數(shù)組元素計數(shù)、增加或刪除元素,或對元素排序。
以下為引用的內容: <? $namesArray = array("Joe", "Jane", "Bob", "Mary", "Paul", "Eddie", "John"); $lookingFor = "Albert"; if (in_array($lookingFor, $namesArray)) { echo "You've found it!"; } else { echo "Not found in this array!"; } ?> |
如果你改變了$lookingFor的值,將其變?yōu)?ldquo;Mary”,你將得到消息“You've found it!”——因為“Mary”是$namesArray的一部分。
如果希望對數(shù)組元素計數(shù),你可以使用count()函數(shù):
以下為引用的內容: <? $namesArray = array("Joe", "Jane", "Bob", "Mary", "Paul", "Eddie", "John"); $count = count($namesArray); ?> $count值將為7。 |
你可以對任何數(shù)組添加元素,無論是在已存在數(shù)組的開始或末尾。你也可以使用函數(shù)以創(chuàng)建一個包含兩個或多個數(shù)組元素的新數(shù)組。合并時每個數(shù)組將按需要的順序排列。如果你的數(shù)組已經有內部的排序,你需要對新的合并數(shù)組重排序。
讓我們從對已存在數(shù)組的末尾增添元素開始,使用函數(shù)array_push():
以下為引用的內容: <? /* 創(chuàng)建原始數(shù)組 */ $fruitArray = array("apple", "orange", "banana", "kiwi", "pear"); /* 加入到原始數(shù)組中 */ array_push($fruitArray, "grape", "pineapple", "tomato"); /* 通過其鍵值列出每個元素*/ while (list($key,$value) = each($fruitArray)) { echo "$key : $value<br>"; } ?> |
這將顯示:
以下為引用的內容: 0 : apple 1 : orange 2 : banana 3 : kiwi 4 : pear 5 : grape 6 : pineapple 7 : tomato |
當你需要對數(shù)組開頭添加元素時,代碼非常類似。不同處只是函數(shù)名:array_unshift() 而不是array_push()。
以下為引用的內容: <? /* 創(chuàng)建原始數(shù)組 */ $fruitArray = array("apple", "orange", "banana", "kiwi", "pear"); /* 加入到原始數(shù)組中 */ array_unshift($fruitArray, "grape", "pineapple", "tomato"); /* 通過其鍵值列出每個元素*/ while (list($key,$value) = each($fruitArray)) { echo "$key : $value<br>"; } ?> |
這將顯示:
以下為引用的內容: 0 : grape 1 : pineapple 2 : tomato 3 : apple 4 : orange 5 : banana 6 : kiwi 7 : pear |
函數(shù)array_merge()合并兩個或更多的數(shù)組。
以下為引用的內容: <? /* 創(chuàng)建原始數(shù)組 */ $fruitArray = array("apple", "orange", "banana", "kiwi", "pear"); <? /* 創(chuàng)建第二個數(shù)組 */ $vegArray = array("carrot", "green beans", "asparagus", "artichoke", "corn"); /* 合并為一個數(shù)組 */ $goodfoodArray = array_merge($fruitArray, $vegArray); /* 通過其鍵值列出每個元素*/ while (list($key,$value) = each($goodfoodArray)) { echo "$key : $value<br>"; } ?> |
這將顯示:
以下為引用的內容: 0 : apple 1 : orange 2 : banana 3 : kiwi 4 : pear 5 : carrot 6 : green beans 7 : asparagus 8 : artichoke 9 : corn |
現(xiàn)在已經對數(shù)組進行了增加元素和合并,現(xiàn)在來練習刪除元素函數(shù)。你可以使用函數(shù)array_pop()從一數(shù)組末尾刪除一個元素。如果使用函數(shù) array_shift(),則從一數(shù)組開頭刪除一個元素。而實際上當你從數(shù)組刪除元素時,此元素對你而言仍然可用——當你從已存在的數(shù)組中對元素進行 pop 或 shift時。
上一篇 網絡營銷論壇運營一個月的感受