PHP removes elements from an array in several ways, and this article summarizes several ways to delete an array of elements in PHP and to remove multiple elements from an array. Well, don't say much, let's take a direct look at the text.
To delete an element in an array
If you want to delete an element from an array, you can use the unset () or Array_splice () method.
If you know the value of the array element, but do not know the key, you can use Array_search () to get the key (key).
Unset () method
Note If you use the unset () method, it is not going to change the other key (key), and if you want to rearrange the sort of other keys (key), you can use Array_values ().
<?php$array = Array (0 = "a", 1 = "B", 2 = "C"); unset ($array [1]); ↑ you want to delete the array element value of the key Print_r ($array);? >
Output Result:
Array ( [0] = a [2] = c)
Array_splice () method
If you use the Array_splice () method, the keys of the array are automatically re-indexed, but the associative arrays do not work, and you need to use Array_values () to convert the keys to numeric keys.
<?php$array = Array (0 = "a", 1 = "B", 2 = "C"); Array_splice ($array, 1, 1); ↑offset which you want to Deleteprint_r ($array);? >
Output Result:
Array ( [0] = a [1] = c)
Array_splice () takes the same action as the unset () function on the release array on the specified element.
Remove multiple elements from an array
If you want to delete multiple elements in an array, you cannot use the unset () or Array_splice () function, you need to use the Array_diff () or the Array_diff_key () method, which requires you to know the key (key) or value to be deleted (value )。
Array_diff () method
If you know the array element you want to delete, you can use Array_diff ().
<?php$array = Array (0 = "a", 1 = "B", 2 = "C"), $array = Array_diff ($array, ["A", "C"]); └────────┘→ you want to delete the element Print_r ($array);? >
The output is:
Array ( [1] = b)
Array_diff_key () method
If you know the key of the array element you want to delete, you can use Array_diff_key (). You need to enter the key of the second parameter of the function to delete the keys, the value does not need, can be arbitrary.
<?php$array = Array (0 = "a", 1 = "B", 2 = "C"), $array = Array_diff_key ($array, [0 = "XY", "2" = "XY") "]); ↑ ↑ The array key you want to delete Print_r ($array);? >
The output is:
Array ( [1] = b)