Home > Article > Backend Development > How to delete array elements based on key in PHP
Given an array (one or more dimensions), the task is to delete an array element based on the key value.
The example is as follows:
输入: Array ( [0] => 'G' [1] => 'E' [2] => 'E' [3] => 'K' [4] => 'S' ) Key = 2 输出: Array ( [0] => 'G' [1] => 'E' [3] => 'K' [4] => 'S' )
Use the unset() function: The unset() function is used to delete elements from an array. The unset function is used to destroy any other variable and is also used to delete any element of an array. This unset command takes an array key as input and removes the element from the array. After deletion, the associated keys and values do not change.
Syntax:
unset($variable)
Parameters: This function accepts a single parameter variable. It is a required parameter and is used to unset the element.
Procedure 1: Remove elements from a one-dimensional array.
<?php $arr = array('G', 'E', 'E', 'K', 'S'); print_r($arr); unset($arr[2]); print_r($arr); ?>
Output:
Array ( [0] => G [1] => E [2] => E [3] => K [4] => S ) Array ( [0] => G [1] => E [3] => K [4] => S )
Program 2: Remove elements from an associative array.
<?php $marks = array( "Ankit" => array( "C" => 95, "DCO" => 85, ), "Ram" => array( "C" => 78, "DCO" => 98, ), "Anoop" => array( "C" => 88, "DCO" => 46, ), ); echo "删除元素前 <br>"; print_r($marks); unset($marks["Ram"]); echo "删除元素后 <br>"; print_r($marks); ?>
Output:
删除元素前 Array ( [Ankit] => Array ( [C] => 95 [DCO] => 85 ) [Ram] => Array ( [C] => 78 [DCO] => 98 ) [Anoop] => Array ( [C] => 88 [DCO] => 46 ) ) 删除元素后 Array ( [Ankit] => Array ( [C] => 95 [DCO] => 85 ) [Anoop] => Array ( [C] => 88 [DCO] => 46 ) )
Recommendation: "PHP Tutorial"
This article is about how to delete key-based keys in PHP The method introduction of array elements is simple and easy to understand. I hope it will be helpful to friends in need!
The above is the detailed content of How to delete array elements based on key in PHP. For more information, please follow other related articles on the PHP Chinese website!