PHP gets and deletes the first and last elements of an array

Source: Internet
Author: User

How do I get and delete the first or last element of an array in PHP? In fact, both of these processes can be done through PHP's own functions Array_pop and Array_shift, the following is a detailed description of how to operate.
(1) Use Array_pop to delete the last element of an array, for example:
$arr =array (' A ', ' B ', ' C ');
$result =array_pop ($arr);
Print_r ($result);
Print_r ($arr);
The result will be:
C
Array (' A ', ' B ')

(2) Use Array_shift to delete the first element of an array, for example:
$arr =array (' A ', ' B ', ' C ');
$result =array_shift ($arr);
Print_r ($result);
Print_r ($arr);
The result will be:
A
Array (' B ', ' C ')
In fact, the first element of the delete array can also use the Array_splice function, namely:

Deleting the first element of an array can also use the Array_splice function, which is:

$arr =array_splice ($arr, 1); Delete the first element of the array, and note that the new array is returned when it is deleted

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's length. If array is empty (or not an array), NULL is returned.
Array_shift () Moves the first cell of the array out and returns as a result, reducing the length of the array and moving all other cells forward one bit. All numeric key names are changed from zero to start, and the text key name is unchanged. If the array is empty (or not an array), NULL is returned.

PHP gets and deletes the first and last elements of 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.