[精讚] [會員登入]
5337

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] 使用browscap檢查瀏覽器版本 使用PHP內建函數browscap檢查瀏覽器版本

[PHP] 處理mail 函式的標題中文字亂碼 PHP的mail函式若標題有中文字得先處理過,否則收信者會看到亂碼

[phpmyadmin] 錯誤:您應升級到 MySQL 5.5.0 或更新版本 使用phpmyadmin4出現錯誤:您應升級到 MySQL 5.5.0 或更新版本的解決方式

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

[PHP+ci4] codeignitor4+ smarty5 這篇整合 php 的framework codeignitor4 + smarty5。

[PHP] 字串拆解函數substr 奇異的錯誤(札記) 偶然發現一個 substr函數拆解上的怪異之處

隨機好文

談借錢 人借錢時手心向上頭向下,人還錢時手心向下頭向上

[CodeIgniter3] 解決無法上傳特定檔案(.sb2)的問題 上傳時出現The filetype you are attempting to upload is not allowed,要怎麼解決?

維修冰箱 維修冰箱

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

[AS3] 變數型態 基本類型宣告 as3 有下列幾種基本類型:string, int, number, object, boolean, n