如何在PHP中基于键删除数组元素
本文向大家介绍如何在PHP中基于键删除数组元素,包括了如何在PHP中基于键删除数组元素的使用技巧和注意事项,需要的朋友参考一下
要基于PHP中的键删除数组元素,代码如下-
示例
<?php $arr = array( " John ", "Jacob ", " Tom ", " Tim "); echo "具有前导和尾随空格的数组...\n"; foreach( $arr as $value ) { echo "Value = $value \n"; } echo "\n逗号分隔列表...\n"; print_r(implode(', ', $arr)); $result = array_map('trim', $arr); echo "\n更新后的数组...\n"; foreach( $result as $value ) { echo "Value = $value \n"; } unset($result[1]); echo "\n更新后的数组...\n"; foreach( $result as $value ) { echo "Value = $value \n"; } ?>
输出结果
具有前导和尾随空格的数组... Value = John Value = Jacob Value = Tom Value = Tim 逗号分隔列表... John , Jacob , Tom , Tim 更新后的数组... Value = John Value = Jacob Value = Tom Value = Tim 更新后的数组... Value = John Value = Tom Value = Tim
示例
现在让我们来看另一个示例-
<?php $marks = array( "kevin" => array ( "physics" => 95, "maths" => 90, ), "ryan" => array ( "physics" => 92, "maths" => 97, ), ); echo "kevin 的物理成绩 : " ; echo $marks['kevin']['physics'] . "\n"; echo "ryan 的数学成绩 : "; echo $marks['ryan']['maths'] . "\n"; unset($marks["ryan"]); echo "ryan 的数学成绩 : "; echo $marks['ryan']['maths'] . "\n"; ?>
输出结果
这将产生以下输出。现在,由于我们删除了该元素并尝试访问该元素,因此将看到一个错误-
kevin 的物理成绩 : 95 ryan 的数学成绩 : 97 ryan 的数学成绩 : PHP Notice: Undefined index: ryan in /home/cg/root/6985034/main.php on line 25