Home >Backend Development >PHP Problem >How to remove elements from one-dimensional array in php
Removal method: 1. Use array_shift() to delete the first element, the syntax is "array_shift(array)". 2. Use array_pop() to delete the last element, the syntax is "array_pop(array)". 3. Use array_splice() to delete the specified number of elements starting from the specified position. The syntax is "array_splice(array, position, number);". 4. Use array_slice() to delete elements and retain the specified number of elements starting from the specified position.
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
php removes one dimension 4 methods of array elements
1. Use the array_shift() function
array_shift() function is used to delete the first element in the array element and returns the deleted element. Note: This function can change the original array.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(1,2,3,4,5,6,7,8,9); var_dump($arr); array_shift($arr); var_dump($arr); ?>
2. Use array_pop() function
array_pop() function to delete the last element in the array. Note: This function can change the original array.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(1,2,3,4,5,6,7,8,9); var_dump($arr); array_pop($arr); var_dump($arr); ?>
3. Use array_splice() function
array_splice() function can delete the specified number of elements starting from the specified position. . Note: This function can change the original array.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); echo "从第二元素开始删除1个元素:" ; array_splice($arr,1,1); var_dump($arr); echo "从第三元素开始删除2个元素:" ; $arr=array(10,12,20,25,24); array_splice($arr,2,2); var_dump($arr); ?>
The third parameter of this function can be omitted, then all remaining elements will be deleted.
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); echo "从第3元素开始删除全部元素:" ; array_splice($arr,2); var_dump($arr); ?>
Method 4: Use array_slice() function
array_slice() function is a function provided by PHP for intercepting arrays Function that extracts a fragment from an array and returns it.
In other words, the array_slice() function can retain the specified number of elements starting from the specified position, and delete other elements.
<?php header("Content-type:text/html;charset=utf-8"); $arr = array(10,12,20,25,24); echo "原数组:"; var_dump($arr); echo "截取的数组片段:"; $result = array_slice($arr,2); //截取从下标2开始的全部数组元素 var_dump($result); $result = array_slice($arr,1,2); //截取从下标1开始的两个元素 var_dump($result); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove elements from one-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!