如何根据PHP的键删除数组元素?
给定一个数组(一维或多维),任务是根据键值删除数组元素。
例子:
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:从一维数组中删除一个元素。
输出:
Array
(
[0] => G
[1] => E
[2] => E
[3] => K
[4] => S
)
Array
(
[0] => G
[1] => E
[3] => K
[4] => S
)
程序2:从关联数组中删除一个元素。
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
";
// Display Results
print_r($marks);
// Use unset() function to
// delete elements
unset($marks["Ram"]);
echo "After delete the element
";
// 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
)
)
PHP是一种专门为 Web 开发设计的服务器端脚本语言。您可以按照此PHP教程和PHP示例从头开始学习PHP 。