Php can delete an array by using the following two methods:
1. Traverse the array and determine whether the element value is specified. If so, use unset () to delete it. The sample code is as follows:
| The code is as follows: |
Copy code |
|
// $ Var is the element value to be deleted, and $ array is the target array;
Function array_del ($ var, $ array ){
$ I = 0;
Foreach ($ array as $ val ){
If ($ var = $ val ){
Unset ($ array [$ I]);
Break;
}
$ I ++;
}
Return $ array;
} |
2. Use the array_flip () function to reverse the key name and value. The sample code is as follows:
| The code is as follows: |
Copy code |
|
<? Php
$ A = array ('php', 'css ', 'Java', 'html', 'jquery ');
$ A = array_flip ($ a); // reverse the key name and value
Unset ($ a ['HTML ']); // deletes a specified value element.
$ A = array_flip ($ a); // reverse the array again to restore the key name and value of the array.
Var_dump ($ );
?> |
Delete an empty element from an array
Instance:
| The code is as follows: |
Copy code |
|
<? Php
$ Array = ('a' => "abc", 'B' => "bcd", 'C' => "cde", 'D' => "def ", 'E' => "");
Array_filter ($ array );
Echo "<pre> ";
Print_r ($ array );
?>
Result:
Array (
[A] => abc
[B] => bcd
[C] => cde
[D] => def
) |
Removes empty and repeated elements from the array.
| The code is as follows: |
Copy code |
|
<? Php
$ Array = array ('2', 19,33, 88,2, 99, '', 33 ,'');
Function delArrayRepeat ($ arr ){
If (is_array ($ arr )){
$ Arr = array_unique ($ arr );
Foreach ($ arr as $ k =>$ v ){
If ($ v = ''){
Unset ($ arr [$ k]);
}
}
$ Result = $ arr;
} Else {
$ Result = "The parameter must be an array! ";
}
Return $ result;
}
$ Res = delArrayRepeat ($ array );
Print_r ($ res );
?> |