Home >Backend Development >PHP Problem >php remove first element of array

php remove first element of array

藏色散人
藏色散人Original
2021-02-20 09:17:242810browse

php method to remove the first element of an array: 1. Use the array_shift() function to delete an element at the beginning of the array, the syntax is "array_shift($arr)"; 2. Use the array_splice() function, the syntax "array_splice($arr,0,1)"; 3. Use the array_slice() function, the syntax is "array_slice($arr,1)".

php remove first element of array

The operating environment of this article: Windows 7 system, PHP 8 version, DELL G3 computer.

Method 1: Use the array_shift() function

Create a PHP file and define an array, example:

$arr = array('apple', 'orange', 'banana', 'watermelon');

php remove first element of array

Format and output the original content of the array, example:

echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($arr);
echo &#39;<pre class="brush:php;toolbar:false">&#39;;

php remove first element of array

Save the above file and preview the original array content on the screen

php remove first element of array

Use array_shift() to delete the first element in the array, example:

echo array_shift($arr);

php remove first element of array

Save the above content and preview it on the screen again, The deleted element value will be printed on the screen

php remove first element of array

#Format and output the data in the array after the first element is deleted

php remove first element of array

Save the above content and preview the final effect

php remove first element of array

Method 2: Use the array_splice() function

## The #array_splice() function is used to delete part of the elements of the array; you can delete them directly or replace them with other values.

Example: Delete the first element in the array

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(10,12,20,25,24);
echo "原数组:";
var_dump($arr);

array_splice($arr, 0,1);

echo "删除后的数组:" ;
var_dump($arr);
?>

php remove first element of array

Method 3: Use the array_slice() function

array_slice() function is used to intercept an array, that is, to extract a fragment from the array.

Return value: Return the intercepted subarray.

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array(12,20,25,24,26);
echo "原数组:";
var_dump($arr);

echo "删除后的数组:" ;
var_dump(array_slice($arr, 1));
?>

php remove first element of array

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of php remove first element of array. For more information, please follow other related articles on the PHP Chinese website!

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