如何在 PHP 中根据键删除数组元素?


要删除 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...
";    foreach( $result 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...
Value = John
Value = Tom
Value = Tim

示例

我们现在来看另一个示例:

 实时演示

<?php
   $marks = array(
      "kevin" => array (
         "physics" => 95,
         "maths" => 90,
      ),
      "ryan" => array (
         "physics" => 92,
         "maths" => 97,
      ),
   );
   echo "Marks for kevin in physics : " ;
   echo $marks['kevin']['physics'] . "
";    echo "Marks for ryan in maths : ";    echo $marks['ryan']['maths'] . "
";    unset($marks["ryan"]);    echo "Marks for ryan in maths : ";    echo $marks['ryan']['maths'] . "
"; ?>

输出

这将产生以下输出。现在,将显示一条错误,因为我们删除了元素并尝试访问它:

Marks for kevin in physics : 95
Marks for ryan in maths : 97
Marks for ryan in maths :
PHP Notice: Undefined index: ryan in /home/cg/root/6985034/main.php on line 25

更新于: 2019 年 12 月 27 日

693 次浏览

开启你的 职业生涯

完成课程以获得认证

入门
广告