PHP的陣列加項目很簡單,直接給定即可,不必宣告
1 2 3 | $arr [ 'one' ] = "apple" ; $arr [2] = "pineapple" ; |
使用array_push函數
直接使用 array_push():
1 2 3 4 | $arr = array ( "red" , "yellow" , "orange" ); array_push ( $arr , "green" , "blue" , "black" ); print_r( $arr ); //Array ( [0] => red [1] => yellow [2] => orange [3] => green [4] => blue [5] => black ) |
另一個範例,不管中間有少了索引1的項目,還是會把項目加在後面
1 2 3 4 | $arr = array (0=> "red" ,3=> "yellow" ,2=> "orange" ); //Lack of index 1 array_push ( $arr , "green" , "blue" , "black" ); print_r( $arr ); //Array ( [0] => red [3] => yellow [2] => orange [4] => green [5] => blue [6] => black ) |
使用array_push 一次可加多個項目。
使用空白中刮號 []
中刮號的加項目法也很方便
1 2 3 4 5 6 | $arr = array (0=> "red" ,5=> "orange" ); $arr []= "green" ; $arr []= "blue" ; $arr []= "black" ; print_r( $arr ); // Array ( [0] => red [5] => orange [6] => green [7] => blue [8] => black ) |
整理陣列索引
重新把索引號整理過
上面的例子如果使用 array_values 可以把陣列的索引值重新整理
1 2 3 | $arr = array_values ( $arr ); print_r( $arr ); // Array ( [0] => red [1] => orange [2] => green [3] => blue [4] => black ) |
做個簡單的筆記
原文 2010-11-02