PHP Four method instances for removing elements from an array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.