PHP array Delete element re-index method

Source: Internet
Author: User

Deleting an element in an array can be used directly with the unset, the missing element will be filled and the array will be re-indexed.

If you want to delete an element in an array, you can use the unset directly:

<? PHP $arr Array (' A ', ' B ', ' C ', ' d '); unset ($arr[1]); Print_r ($arr);? >

Print_r ($arr), the result is not that, the end result is an Array ([0] = a [2] = c [3] + D)
So how can the missing elements be filled and the array will be re-indexed? The answer is
Array_splice (): www.jbxue.com

<? PHP $arr Array (' A ', ' B ', ' C ', ' d '); Array_splice ($arr, (); Print_r ($arr);? >

Print_r ($arr), the result is a (www.jb51.net) Rray ([0] = a [1] = + c [2] + D)
To delete an array-specified element
Array_search () more practical
The 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

$array Array (' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 '); $del _value = 3; unset ($array[array_search($del _value$array)]); // Delete this element using unset Print_r ($array);

Output
Array (' 1 ', ' 2 ', ' 4 ', ' 5 ');
It is also possible to re-index an array if you need to re-establish an array after using a foreach traversal of the deleted array.

PHP array Delete element re-index method

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.