Home >Backend Development >PHP Problem >How to remove two values from an array in php
Two removal methods: 1. Call the unset() function twice to delete two elements respectively, the syntax is "unset(array name [subscript/key name])"; 2. Use the array_splice() function Delete two elements from the specified position in the array, the syntax is "array_splice($arr, starting position, 2)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php removes the array two Two methods for a value
Method 1: Call the unset() function twice to delete two elements
The unset() function can Delete a specified element
Syntax:
unset(数组名[下标]); //删除索引数组中的一个元素 unset(数组名["键名"]); //关联数组中的一个元素
Example 1:
<?php $arr=array(1,2,3,4,5,6); var_dump($arr); unset($arr[2]); unset($arr[3]); var_dump($arr); ?>
Example 2:
<?php $arr=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"blue"); var_dump($arr); unset($arr["b"]); unset($arr["d"]); var_dump($arr); ?>
Method 2: Use the array_splice() function
When the array_splice() function deletes some elements of the array, it will form these deleted elements into a new one. array.
Example 1: Delete 2 elements from the array from the beginning
<?php header('content-type:text/html;charset=utf-8'); $arr = array(10,12,20,25,24,11,22,34,55); echo "原数组:"; var_dump($arr); echo "从开头删除数组2个元素:"; array_splice($arr,0,2); //删除数组2个元素 var_dump($arr); ?>
Example 2: Delete 2 elements from the array after the 1st element
<?php header('content-type:text/html;charset=utf-8'); $arr = array(10,12,20,25,24,11,22,34,55); echo "原数组:"; var_dump($arr); echo "从第1个元素后删除数组2个元素:"; array_splice($arr,1,2); //删除数组2个元素 var_dump($arr); ?>
Example 3: Delete 2 elements from the array after the 2nd element
<?php header('content-type:text/html;charset=utf-8'); $arr = array(10,12,20,25,24,11,22,34,55); echo "原数组:"; var_dump($arr); echo "从第2个元素后删除数组2个元素:"; array_splice($arr,2,2); //删除数组2个元素 var_dump($arr); ?>
Recommended learning:《PHP video tutorial》
The above is the detailed content of How to remove two values from an array in php. For more information, please follow other related articles on the PHP Chinese website!