Php example of deleting array elements _ PHP Tutorial

Source: Internet
Author: User
Example of deleting array elements in php. PHP: 1. use the unset () method: Copy the code as follows :? Php $ aarray (red, green, blue, yellow); count ($ a); get 4 unset ($ a [1]); delete the PHP-specific method for deleting array elements:

1. use the unset () method:

The code is as follows:


$ A = array ("red", "green", "blue", "yellow ");
Count ($ a); // Get 4
Unset ($ a [1]); // deletes the second element.
Count ($ a); // Get 3
Echo $ a [2]; // The array contains only three elements. In this example, we want to get the last element, but we get blue,
Echo $ a [1]; // no value
?>

Disadvantage: after the elements in the array are deleted, the number of elements in the array (obtained by count () has changed, but the array subscript has not been rearranged, you must also use PHP to delete the key before the array element to operate the corresponding value.

2. use the array_splice () method:

The code is as follows:


$ A = array ("red", "green", "blue", "yellow ");
Count ($ a); // Get 4
Array_splice ($ a,); // deletes the second element.
Count ($ a); // Get 3
Echo $ a [2]; // obtain yellow
Echo $ a [1]; // Get blue
?>

Compared with the previous one, we can see that array_splice () not only deletes the elements, but also rearranges the elements so that no null value exists between the elements in the array!

Example 1. use the unset () method: the code is as follows :? Php $ a = array ("red", "green", "blue", "yellow"); count ($ ); // Get 4 unset ($ a [1]); // delete...

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.