给定一个数组(一维或多维), 任务是根据键值删除数组元素。
例子:
Input: Array
(
[0] => 'G'
[1] => 'E'
[2] => 'E'
[3] => 'K'
[4] => 'S'
)
Key = 2
Output: Array
(
[0] => 'G'
[1] => 'E'
[3] => 'K'
[4] => 'S'
)
使用unset()函数:unset()函数用于从数组中删除元素。 unset函数用于销毁任何其他变量, 并以相同的方式删除数组的任何元素。此unset命令将数组键作为输入, 并从数组中删除该元素。删除后, 关联的键和值不会更改。
语法如下:
unset($variable)
参数:该函数接受单个参数变量。它是必填参数, 用于取消设置元素。
程序1:从一维数组中删除元素。
<?php
//PHP program to delete an array
//element based on index
//Declare arr variable
//and initialize it
$arr = array ( 'G' , 'E' , 'E' , 'K' , 'S' );
//Display the array element
print_r( $arr );
//Use unset() function delete
//elements
unset( $arr [2]);
//Display the array element
print_r( $arr );
?>
输出如下:
Array
(
[0] => G
[1] => E
[2] => E
[3] => K
[4] => S
)
Array
(
[0] => G
[1] => E
[3] => K
[4] => S
)
程序2:从关联数组中删除一个元素。
<?php
//PHP program to creating two
//dimensional associative array
$marks = array (
//Ankit will act as key
"Ankit" => array (
//Subject and marks are
//the key value pair
"C" => 95, "DCO" => 85, ), //Ram will act as key
"Ram" => array (
//Subject and marks are
//the key value pair
"C" => 78, "DCO" => 98, ), //Anoop will act as key
"Anoop" => array (
//Subject and marks are
//the key value pair
"C" => 88, "DCO" => 46, ), );
echo "Before delete the element <br>" ;
//Display Results
print_r( $marks );
//Use unset() function to
//delete elements
unset( $marks [ "Ram" ]);
echo "After delete the element <br>" ;
//Display Results
print_r( $marks );
?>
输出如下:
Before delete the element Array
(
[Ankit] => Array
(
[C] => 95
[DCO] => 85
)
[Ram] => Array
(
[C] => 78
[DCO] => 98
)
[Anoop] => Array
(
[C] => 88
[DCO] => 46
)
)
After delete the element Array
(
[Ankit] => Array
(
[C] => 95
[DCO] => 85
)
[Anoop] => Array
(
[C] => 88
[DCO] => 46
)
)