To delete an element from an array and use unset directly, how can we fill in the missing element and re-index the array, the following will reveal the unset that can be used directly if you want to delete an element in an array, but what you see today surprised me.
The code is as follows:
<? Php
$ Arr = array ('A', 'B', 'C', 'D ');
Unset ($ arr [1]);
Print_r ($ arr );
?>
After print_r ($ arr), the result is not that. The final result is Array ([0] => a [2] => c [3] => d)
So how can we fill in the missing elements and re-index the array? The answer is:
Array_splice ():
The code is as follows:
<? Php
$ Arr = array ('A', 'B', 'C', 'D ');
Array_splice ($ arr, 1, 1 );
Print_r ($ arr );
?>
After print_r ($ arr), the result is A (www.jb51.net) rray ([0] => a [1] => c [2] => d)
Deletes the specified element of an array.
Array_search () is more practical.
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 ');
However, if you want to re-index the array, you need to use foreach to traverse the deleted array and re-create an array.