Summary of the php method for deleting array elements. 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, 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: |
|
|
$ 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: |
|
|
$ 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: |
|
|
$ 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: |
|
|
$ Array = ('a' => "abc", 'B' => "bcd", 'C' => "cde", 'D' => "def ", 'E' => "");
Array_filter ($ array );
Echo"
"; 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: |
|
|
Function array_remove (& $ arr, $ offset ){
Array_splice ($ arr, $ offset, 1 );
}
$ A = array ('A', 'B', 'C', 'D ');
Array_remove ($ a, 2 );
Print_r ($ ); |
...