This article mainly introduces PHP from the array to remove elements of the four methods of the example, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.
Anise Bean's "anise" word has four kinds of wording, PHP removed from the array of elements there are four ways ^_^.
Deletes an element and keeps the original index intact
Using the unset function, the example is as follows:
<?php $array = Array (0 = "a", 1 = "B", 2 = "C"); Unset ($array [1]); ↑ you want to delete the key?>
Output:
Array (
[0] = a
[2] = C
)
Using unset does not alter the original index of the array. If you plan to rearrange the index (let the index start at 0 and continue), you can use the Array_values function:
$array = Array_values ($array);/* Output Array (2) {[0]=> string (1) "A" [1]=> string (1) "C"}*/
Delete an element without keeping the index
Using the Array_splice function, the example is as follows:
<?php $array = Array (0 = "a", 1 = "B", 2 = "C"); Array_splice ($array, 1, 1); ↑ The offset?> of the element you wish to remove
Output:
Array (
[0] = a
[1] = C
)
Delete multiple elements by value, keep index
Using the Array_diff function, the example is as follows:
<?php $array = Array (0 = "a", 1 = "B", 2 = "C"); $array = Array_diff ($array, ["A", "C"]); └────────┘→ the array element value you want to delete values?>
Output:
Array (
[1] = b
)
Similar to unset, Array_diff will also remain indexed.
Key to delete multiple elements, keep index
Using the Array_diff_key function, the example is as follows:
<?php $array = Array (0 = "a", 1 = "B", 2 = "C"); $array = Array_diff_key ($array, [0 = "XY", "2" = "XY"]); ↑ ↑ You want to delete the array key keys?>
Output:
Array (
[1] = b
)
Similar to unset, Array_diff_key will also remain indexed.
PHP Four method instances for removing elements from an array