Example of deleting array elements in php

Source: Internet
Author: User

Example of deleting array elements in php

This article describes how to delete array elements in php. For more information, see

PHP:

 

1. Use the unset () method:

 

The Code is as follows:

<? Php

$ 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:

<? Php

$ 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!

 

 

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.