php 中可使用多種方法刪除數(shù)組元素,包括:使用 unset() 函數(shù)永久刪除指定鍵或索引的元素;使用 array_splice() 函數(shù)從指定偏移量開始刪除一定數(shù)量的元素;使用 array_diff() 函數(shù)創(chuàng)建包含兩個或更多數(shù)組差異的新數(shù)組,并刪除出現(xiàn)在第二個數(shù)組中的元素;使用 array_filter() 函數(shù)創(chuàng)建包含通過指定回調(diào)函數(shù)的元素的新數(shù)組,可刪除不滿足條件的元素。
PHP 中刪除數(shù)組元素
PHP 提供了多種方法來從數(shù)組中刪除元素。
1. unset() 函數(shù)
使用 unset() 函數(shù)可以永久刪除指定鍵或索引的元素:
<code class="php">$array = ['foo' => 'bar', 'baz' => 'qux']; unset($array['foo']);</code>
登錄后復(fù)制
2. array_splice() 函數(shù)
array_splice() 函數(shù)可以刪除一定數(shù)量的元素,從指定的偏移量開始:
<code class="php">$array = ['foo', 'bar', 'baz', 'qux']; array_splice($array, 1, 2); // 從索引為 1 開始刪除 2 個元素</code>
登錄后復(fù)制
3. array_diff() 函數(shù)
array_diff() 函數(shù)可以創(chuàng)建一個新的數(shù)組,其中包含兩個或更多數(shù)組之間的差異,并刪除出現(xiàn)在第二個數(shù)組中的元素:
<code class="php">$array1 = ['foo', 'bar', 'baz']; $array2 = ['bar', 'qux']; $result = array_diff($array1, $array2); // ['foo', 'baz']</code>
登錄后復(fù)制
4. array_filter() 函數(shù)
array_filter() 函數(shù)可以創(chuàng)建一個新的數(shù)組,其中包含通過指定回調(diào)函數(shù)的元素,可以將不滿足條件的元素刪除:
<code class="php">$array = ['foo', 'bar', 'baz', null];
$result = array_filter($array, function ($value) {
return $value !== null;
}); // ['foo', 'bar', 'baz']</code>
登錄后復(fù)制






