[精讚] [會員登入]
5323

[PHP] 陣列新增資料及整理

在php陣列加入項目和重新整理陣列的方法

分享此文連結 //n.sfs.tw/12800

分享連結 [PHP] 陣列新增資料及整理@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-25 11:19:55 最後編修
2018-10-12 01:17:58 By 張○○
 

自動目錄

PHP的陣列加項目很簡單,直接給定即可,不必宣告

$arr['one'] = "apple";

$arr[2] = "pineapple";

 

使用array_push函數

 

直接使用 array_push():

 

$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的項目,還是會把項目加在後面

$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 一次可加多個項目。

 

使用空白中刮號 []

中刮號的加項目法也很方便

$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 可以把陣列的索引值重新整理

$arr=array_values($arr);
print_r($arr);
// Array ( [0] => red [1] => orange [2] => green [3] => blue [4] => black )

做個簡單的筆記

 


原文 2010-11-02

END

你可能感興趣的文章

[CodeIgniter 3] 取得controller和method的方法 CodeIgniter 3 取得controller和method的方法

[Smarty5] 如何在樣版中使用php本身的函式 解決 smarty5版後不能直接叫用 php函式的問題

[PHP>7.3] switch中的 Did you mean to use "continue 2"? 除錯 這近更新 PHP到7.3版以後,出現這樣的錯:targeting switch is equivalent to "break". Did you mean to use "continue 2"?解決方法

PHP 移除陣列中的元素 要移除陣列中的其中一項元素

[PHP] CodeIgniter 3+pure+smarty安裝及環境設置1/2 PHP framework CodeIgniter 3+ pure CSS +smarty Template Engine的整合

設定Google analytics API #1 -- Google網站上的設定 讓你的網站能夠存取你的Google analytics上面的資料

隨機好文

[Windows7] 移除IE10及移除IE11 Windows7 不得已的情況要移除IE11或IE10怎麼做?

[bc] linux 的計算機 bc 設定小數位數、計算π、次方根 linux 的計算機 bc 設定小數位數、計算π、次方根

[JAVA] JWS, JWT, JWE, JOSE是什麼? [JAVA] JWS, JWT, JWE, JOSE是什麼?非常的複雜,儘量來搞清楚..

UTF-8的網頁但IE8一片空白 UTF8編碼的網頁在Firefox 正常顯示、但IE8 就是空白,IE8編碼設定是「自動偵測」可是自動偵測到的是 big5...

[PHP] 檢查檔案是否是圖檔 使用getimagesize函數檢查檔案是否是圖檔