- 5 years ago
- Zaid Bin Khalid
- 15,595 Views
-
8
In this tutorial, I am going to show you how you can delete an array element with a key value in PHP. We use the PHP UNSET function to delete the array element. However, PHP unset function is used to destroy the specified variable. In the same way, we can use this function to delete an element of an array.
Example Code Below
unset ( mixed$var
[, mixed$...
] ) : void
<?php
$input = array(0=>'a',1=>'b',2=>'c',3=>'d',4=>'e',5=>'f',6=>'g');
unset($input[3]);
foreach($input as $key=>$val){
$inputNew[] = $val;
}
print"<pre>";
print_r($inputNew);
print"</pre>";
?>
//The output will be
Array
(
[0] => a
[1] => b
[2] => c
[3] => e
[4] => f
[5] => g
)
In the output, you can see the index 3 or key of array 3 with the value of d does not exist in a new array. So in this way you can delete any element based on a key in PHP.
Pass Multiple Keys & Delete Array elements.
If you want to remove array elements with multiple keys you can do that. For that, you need to consider the below function.
function removeRecursive($inputArray,$delKey){
if(is_array($inputArray)){
$moreKey = explode(",",$delKey);
foreach($moreKey as $nKey){
unset($inputArray[$nKey]);
foreach($inputArray as $k=>$value) {
$inputArray[$k] = removeRecursive($value,$nKey);
}
}
}
return $inputArray;
}
//Pass multiple keys with comma saperated.
$inputNew = removeRecursive($input,'key1,key2,key3');
The above function is used to remove multiple array elements based on multiple keys. To check just copy and paste below example code in your PHP file and run the file.
Example Code To Remove Multiple values
<?php
$input = array(
0=>'a',
1=>'b',
2=>'c',
array(
4=>'d',
5=>'e',
),
array(
7=>'f',
8=>'g',
)
);
print"<pre>";
print_r($input);
print"</pre>";
function removeRecursive($inputArray,$delKey){
if(is_array($inputArray)){
$moreKey = explode(",",$delKey);
foreach($moreKey as $nKey){
unset($inputArray[$nKey]);
foreach($inputArray as $k=>$value) {
$inputArray[$k] = removeRecursive($value,$nKey);
}
}
}
return $inputArray;
}
$inputNew = removeRecursive($input,'5,1');
print"<pre>";
print_r($inputNew);
print"</pre>";
?>
The out put will be.
Array
(
[0] => a
[1] => b
[2] => c
[3] => Array
(
[4] => d
[5] => e
)
[4] => Array
(
[7] => f
[8] => g
)
)
//NEW ARRAY AFTER REMOVE
Array
(
[0] => a
[2] => c
[3] => Array
(
[4] => d
)
[4] => Array
(
[7] => f
[8] => g
)
)
- 5 years ago
- Zaid Bin Khalid
- 15,595 Views
-
8