PHP deletes the specified key (full version, encapsulated into function, with test code) in array arrays

Source: Internet
Author: User
problem background: Array is generally key---value storage, we sometimes need to delete the specified key and corresponding value. But I do not know why, so many of the posts are talking about knowing the value, and delete the value of things, almost misled me.

Now I am writing the full version of the Code attached:

function Array_remove ($data, $key) {    if (!array_key_exists ($key, $data)) {        return $data;    }    $keys = Array_keys ($data);    $index = Array_search ($key, $keys);    if ($index!== FALSE) {        array_splice ($data, $index, 1);    }    return $data;} $data = Array (' name ' = ' apple ', ' age ' =>12, ' address ' = ' Chinaguangzhou '); $result = Array_remove ($data, ' name ') ; Var_dump ($result);

Additional notes:

1, in fact, the problem is array_search this function, the function according to value to search, get the position, if not found on the return null or false;

2, therefore, in the key to find the corresponding position of key, need to find in the $keys, this is the reason to call Array_keys

3, because array_search this function may return null and false, so the absolute comparison must be used! = =

Reference:

PHP Official Document: http://www.php100.com/cover/php/189.html

Welcome to join PHP CodeIgniter community Group: 460132647 Remarks: Yanzi

The above describes the PHP delete array in the specified key (full version, has been encapsulated into functions, with test code), including the aspects of the content, I hope to be interested in PHP tutorial friends helpful.

  • Related Article

    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.