PHP Two ways to delete array elements unset,array_splice usage differences

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

Result: Array ([0] = a [2] = c [3] + D) How does the missing element be filled and the array will be re-indexed? The answer is Array_splice ():

Example:

    1. $arr = Array (' A ', ' B ', ' C ', ' d ');
    2. Array_splice ($arr, 1, 1);
    3. Print_r ($arr);
    4. ?>
Copy Code

Result: Array ([0] = a [1] = c [2] + D) Delete the specific element in the array (bbs.it-home.org script Academy):

    1. $arr 2 = Array (1, 3, 5,7,8);
    2. foreach ($arr 2 as $key = $value)
    3. {
    4. if ($value = = = 3)
    5. unset ($arr 2[$key]);
    6. }
    7. Var_dump ($arr 2);
    8. ?>
Copy Code

To delete an empty array:

    1. $array = (' a ' + = ' abc ', ' B ' + = ' bcd ', ' c ' = ' CDE ', ' d ' and ' Def ', ' e ' = ' = ') ';
    2. Array_filter ($array);
    3. echo "
      ";
    4. Print_r ($array);
    5. ?>
Copy Code

Result: Array ([a] = ABC + BCD [c] = CDE [d] = def)

Summary: If the Array_splice () function is deleted, the index value of the array also changes. If the unset () function is removed, the index value of the array does not change.

  • 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.