During php development, we often encounter the need to delete the specified content in the array, but the array is a special variable. We cannot directly use replace to replace it. Some operations are required, next I will introduce the operation methods.
If we know the name of the array element, it's easy.
Press the key to delete the specified array element from the array.
| The Code is as follows: |
Copy code |
|
$ Barray = array ('A' => 1, 'B' => 2, 'wod '=> 3, 'c' => 4, 'abc' => 5 );
$ Del = 'B ';
Unset ($ barray [$ del]); // The result is
Array
(
[A] => 1
[Wod] => 3
[C] => 4
[Abc] => 5
)
|
If multiple arrays need to be deleted at the same time, the above method cannot be solved. We can use the array_diff function to operate
Example
| The Code is as follows: |
Copy code |
|
$ A1 = array ("Cat", "Dog", "Horse", 'dff', 'dfdf ', 'www ');
$ A2 = array ("dff", "Horse", "Dog ");
$ A1 = array_diff ($ a1, $ a2 );
Sort ($ a1 );
Print_r ($ a1 );
Array
(
[0] => Cat
[1] => dfdf
[2] => www
) |
Example 2
The array_search () function is the same as the in_array () function. You can find a key value in the array. If this value is found, the key name of the matching element is returned. If not found, false is returned.
| The Code is as follows: |
Copy code |
|
$ Array = array ('1', '2', '3', '4', '5 ');
$ Del_value = 3;
Unset ($ array [array_search ($ del_value, $ array)]); // use unset to delete this element
Print_r ($ array );
Output
Array ('1', '2', '4', '5 '); |
Example
Array_filter ()
Call method: array_filter ($ array)
Parameter description: $ array is the operation object. we will delete the null element.
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
) |
Will indexes be re-created when the above method is deleted? Next I will introduce a method for deleting array elements and recreating array indexes.
| The Code is as follows: |
Copy code |
|
Function array_remove (& $ arr, $ offset ){
Array_splice ($ arr, $ offset, 1 );
}
$ A = array ('A', 'B', 'C', 'D ');
Array_remove ($ a, 2 );
Print_r ($ ); |