如何在 PHP 中從陣列中刪除元素並重新索引陣列?
‘unset’ 函式可用於從陣列中刪除元素,並使用 ‘array_values’ 函式來重置陣列的索引。
示例
<?php $my_arr = array( 'this', 'is', 'a', 'sample', 'only'); echo"The array is "; var_dump($my_arr); unset($my_arr[4]); echo"The array is now "; $my_arr_2 = array_values($my_arr); var_dump($my_arr_2); ?>
輸出
The array is array(5) { [0]=> string(4) "this" [1]=> string(2) "is" [2]=> string(1) "a" [3]=> string(6) "sample" [4]=> string(4) "only" } The array is now array(4) { [0]=> string(4) "this" [1]=> string(2) "is" [2]=> string(1) "a" [3]=> string(6) "sample" }
宣告一個包含字串值的陣列。顯示該陣列,並使用 ‘unset’ 函式從陣列中刪除一個特定索引元素。然後再次顯示該陣列以反映控制檯上的更改。
廣告