Get the App
SLTechnology News&Howtos  ›  Development  › 

How does PHP delete elements in an array

Shulou Source: shulou.com Published: 2022-06-01 22:00:00 09月21日 Update

This article mainly explains "PHP how to delete elements in the array", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "PHP how to delete elements in the array" bar!

Delete an element in the data

If you want to delete an element from the array, you can use the unset () or array_splice () method.

If you know the value of an array element, but not the key, you can use array_search () to get the key.

Unset () method

Note that if you use the unset () method, it will not change the other keys (key), if you want to rearrange the other keys (key), you can use array_values ().

Output result:

Array ([0] = > a [2] = > c)

Array_splice () method

If you use the array_splice () method, the keys of the array will automatically re-index, but will not work on the associative array, you need to use array_values () to convert the key to a numeric key.

Output result:

Array ([0] = > a [1] = > c)

Array_splice () has the same effect as the unset () function on releasing the specified elements of the array.

Delete multiple elements from an array

If you want to delete multiple elements in the array, you can't use the unset () or array_splice () function, you need to use the array_diff () or array_diff_key () method, which requires you to know the key (key) or value (value) to delete.

Array_diff () method

If you know which array elements to delete, you can use array_diff ().

The output is as follows:

Array ([1] = > b)

Array_diff_key () method

If you know the key of the array element to be deleted, you can use array_diff_key (). You need to enter the key to delete in the key position of the second parameter of the function, and the value is optional.

The output is as follows:

Array ([1] = > b) Thank you for your reading, the above is the content of "how to delete elements in the array by PHP". After the study of this article, I believe you have a deeper understanding of how PHP deletes elements in the array, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Array element method result output function learning function content multiple same position relevance parameter that is idea situation number data article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Xiaomi MariaDB MySQL Redmi