How to delete the first and last element of an array in php

怪我咯
Release: 2023-03-12 19:28:02
Original
11885 people have browsed it

This article mainly introduces thefunctionof deleting the first element and the last element of thearray in php. Friends in need can refer to the following

for A

php array, how to delete the first element or the last element of the array? In fact, both processes can be completed through the functionsarray_popandarray_shiftthat come with PHP. Here is a detailed introduction on 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);
Copy after login

The result will be:

orange

array(' apple','banana')

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

$user=array('apple','banana','orange'); $result=array_shift($user); print_r($result); print_r($user);
Copy after login

The result will be:

apple

array('banana','orange')

In fact, you can also use the

array_splicefunction to delete the first element of the array, that is:

The code is as follows:

$user=array_splice($user,1); //删除数组第一个元素,注意此时返回的是被删除后的新的数组
Copy after login

The following is a brief explanation of array_pop and array_shift:

array_pop() pops and returns the last unit of the array array, and reduces the length of the array array by one. NULL will be returned if array is empty (or not an array).

array_shift() Shifts the first element of array out and returns it as the result, decrements the length of array by one and shifts all other elements forward one position. All numeric key names will be changed to count from zero, and text key names will remain unchanged. If array is empty (or is not an array), NULL is returned.

The above is the detailed content of How to delete the first and last element of an array in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!