The function of removing the first element and the last element of an array in PHP _php tips

Source: Internet
Author: User

For a PHP array, how do you delete the first element or the last element of the array? In fact, these two processes can be done with the functions of PHP array_pop and Array_shift to complete, the following is a specific description of how to operate.

(1) Use Array_pop to delete the last element of the array, for example:

$user =array (' Apple ', ' banana ', ' orange ');
$result =array_pop ($user);
Print_r ($result);
Print_r ($user);

The result will be:

Orange
Array (' Apple ', ' banana ')

(2) Use Array_shift to delete the first element of an array, for example:

$user =array (' Apple ', ' banana ', ' orange ');
$result =array_shift ($user);
Print_r ($result);
Print_r ($user);

The result will be:

Apple
Array (' banana ', ' orange ')

In fact, the first element that deletes an array can also use the Array_splice function, which is:

Copy Code code as follows:

$user =array_splice ($user, 1); Delete the first element of the array, notice that the new array is returned at this time

Here's a simple explanation for Array_pop and Array_shift:

Array_pop () pops up and returns the last cell of the array, minus one of the array lengths. If the array is empty (or not an array), it returns NULL.

Array_shift () Moves the first cell of the array out and returns as the result, reducing the length of the array to move all other cells forward one bit. All numeric key names are changed from zero, and the text key is unchanged. Returns null if the array is empty (or not an 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.