[精讚] [會員登入]
5509

PHP 移除陣列中的元素

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

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

分享連結 PHP 移除陣列中的元素@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-25 12:24:42 最後編修
2019-01-11 18:28:08 By 張○○
 

自動目錄

假設一個全數字的陣列

  $ar=array("one","two","three","four","seven","eleven");

我想要移除其中的 "seven" 這個元素,

結果陣列要是

  $arr=array("one","two","three","four","eleven");

 

使用函數

$ar=array("one","two","three","four","seven","eleven");

if (($key = array_search("seven", $ar)) !== false) {
    unset($ar[$key]);
}

 

使用迴圈

$n = sizeof($ar);
for( $ii=0; $ii <$n; $ii++){
    if( $ar[$ii] === "seven") unset($ar[$ii]);
}

注意第三行是 三個等號的運算子 '==='

基本上用迴圈+unset ,不旦直覺而且簡單快速;但是使用函數也可以。

 

參考資料

[1] https://stackoverflow.com/questions/7225070/php-array-delete-by-value-not-key

END

你可能感興趣的文章

[PHP] 好用的php常數 介紹PHP中 __DIR__, __FILE__, __FUNCTION__, __CLASS__, __METHOD__, __LINE__, __NAMESPACE__等常數

[PHP8] 使用autoload autoload+ namespace +use 到了php7之後,namespace和use越來越重要,此篇整理autoload和namespace、use的結合使用。

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

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

使用Yahoo OAuth2 1/2 使用Yahoo OAuth2來認證我的網站

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

隨機好文

NETCRAFT發現你的網站及作業系統 NETCRAFT可以發現你的網站及作業系統

APACHE的記錄檔格式 LogFormat 語法 在APACHE中有定義一些記錄的語法模版 在 /etc/httpd/conf/httpd.conf 中: LogForm

正則表達式:Email名稱防止連續輸入點(.)及下底線(_) Email的名稱中要允許特殊符號,但又不允許連續出現的正則表達式

海棉寶寶超泡杯演奏的sweet victory 章魚哥和海棉寶寶在超泡杯的演奏歌曲

[AS3] FLASH 引入外部as檔 FLASH AS3中,若要引用另外撰寫的 class(*.as) 檔案,該如何處理?