How does the PHP array delete element rebuild the index?

Source: Internet
Author: User
    1. $arr = Array (' A ', ' B ', ' C ', ' d ');
    2. Unset ($arr [1]);
    3. Print_r ($arr);
    4. ?>
Copy Code

Print_r ($arr), the result is not that, the end result is an Array ([0] = a [2] = c [3] + D)

How do I let the missing elements be filled and the array will be re-indexed?

Using Array_splice ():

    1. $arr = Array (' A ', ' B ', ' C ', ' d ');
    2. Array_splice ($arr, 1, 1);
    3. Print_r ($arr);
    4. ?>
    5. Print_r ($arr), the result is a (bbs.it-home.org) Rray ([0] = a [1] = + c [2] + D)
Copy Code

2, delete array specified element Array_search () the utility Array_search () function, like In_array (), looks for a key value in the array. If the value is found, the key name of the matching element is returned. Returns false if not found

    1. $array = Array (' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ');
    2. $del _value = 3;
    3. Unset ($array [Array_search ($del _value, $array)]);//use unset to delete this element
    4. Print_r ($array);
Copy Code

Output Array (' 1 ', ' 2 ', ' 4 ', ' 5 '); If you want to re-index an array, you need to re-establish an array after using the foreach traversal of the deleted 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.