Comparison of Methods for deleting the specified values in an array using php

Source: Internet
Author: User

You also have a function. Many built-in functions in the php tutorial have problems (not an error, but the applicability is narrow)

For (old array .....){
If (the value to be deleted)
Continue
$ NewArr [] = each value
}

Return $ newArr

Instance

Array ([0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day .)

Foreach ($ array as $ k => $ v ){
If ($ v = 'day '){
Unset ($ array [$ k]):
}
}

Using foreach is inefficient. Check the built-in functions of php.

$ Arr = array ("Hello", "world", "It's", "beautiful", "day ");

Instance 1

$ Arr = array_flip ($ arr );

Unset ($ arr ['World']);

$ Arr = array_flip ($ arr );

Print_r ($ arr );

Instance 2

The array_search () function is the same as the in_array () function. You can find a key value in the array. If this value is found, the key name of the matching element is returned. If not found, false is returned.

 

$ Arr = Array ([0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day .);

If ($ key = array_search ('day', $ arr ))){

Unset ($ arr [$ key]);

}


Instance 3

The array_splice () function is similar to the array_slice () function. It selects a series of elements in the array but does not return them. Instead, it deletes them and replaces them with other values.

 

If ($ key = array_search ('day', $ arr ))){

Array_splice ($ arr, $ key, 1 );

}

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.