在 PHP 中删除数组元素和重新分配索引


要删除一个数组元素并对其重新分配索引,其代码如下−

示例

 实践演示

<?php
   $arr = array( " John ", "Jacob ", " Tom ", " Tim ");
   echo "Array with leading and trailing whitespaces...
";    foreach( $arr as $value ) {       echo "Value = $value
";    }    echo "
Comma separated list...
";    print_r(implode(', ', $arr));    $result = array_map('trim', $arr);    echo "
Updated Array...
";    foreach( $result as $value ) {       echo "Value = $value
";    }    unset($result[1]);    echo "
Updated Array...Re-indexed
";    $result2 = array_values($result);    foreach( $result2 as $value ) {       echo "Value = $value
";    } ?>

输出

将产生以下输出−

Array with leading and trailing whitespaces...
Value = John
Value = Jacob
Value = Tom
Value = Tim
Comma separated list...
John , Jacob , Tom , Tim
Updated Array...
Value = John
Value = Jacob
Value = Tom
Value = Tim
Updated Array...Re-indexed
Value = John
Value = Tom
Value = Tim

更新于:2019-12-27

223 次浏览

启动你的 职业生涯

完成课程并获得认证

开始
广告