PHP deletes the specified key in the Array (full version, encapsulated as a function, with test code)

Source: Internet
Author: User
: This article describes how to delete the specified key in the Array in PHP (full version, encapsulated as a function with test code). For more information about PHP tutorials, see. Problem background: the storage method of key-value in array is usually used. we sometimes need to delete the specified key and the corresponding value. But I don't know why, so many posts are about knowing the value and deleting the value, almost misleading me.

The full version code I wrote is now included:

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);

Note:

1. in fact, the problem lies in the array_search function. this function searches by value to obtain the location. if it cannot be found, NULL or false is returned;

2. Therefore, you need to find the corresponding location of the key in $ keys, which is the reason for calling array_keys.

3. because the array_search function may return NULL and false, you must use absolute comparison! =

Refer:

Php official documentation: http://www.php100.com/cover/php/189.html

Welcome to the PHP CodeIgniter community group: 460132647 remarks: yanzi

The preceding section describes how to delete the specified key in the Array in PHP (full version, encapsulated as a function with test code), including the following content, if you are interested in PHP tutorials.

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.