如何在 PHP 中删除数组中的元素并重新索引该数组?

phpserver side programmingprogramming

‘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’函数从数组中删除特定索引元素。然后再次显示该数组以反映控制台上的更改。


相关文章