Home >Backend Development >PHP Problem >How to remove specified elements from an array in php
In PHP, if you need to remove specified elements from an array, there are many ways to do it. Some commonly used methods will be introduced below.
Method 1: Use the unset function
The unset function is used to destroy the specified variables, including elements in the array. You can use the unset function to remove elements at a specified position in the array. The sample code is as follows:
$arr = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'); unset($arr[1]); // 删除索引为 1 的元素 b print_r($arr); // 输出 Array ( [0] => a [2] => c [3] => d )
When deleting array elements through the unset function, you need to pay attention to the following points:
Method 2: Use array_splice function
array_splice function can be used to delete a certain range of elements from an array, and move other elements in the array to corresponding positions to fill the deleted ones Elements. The function prototype is as follows:
array array_splice ( array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]] )
Use the array_splice function to remove the element at the specified position of the array. This can be achieved by passing the position of the element to be removed in the array and the number of elements to be removed to the function:
$arr = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'); array_splice($arr, 1, 1); // 从索引为 1 的位置开始移除 1 个元素 print_r($arr); // 输出 Array ( [0] => a [1] => c [2] => d )
When deleting array elements through the array_splice function, you need to pay attention to the following points:
Method 3: Use array_diff function
array_diff function can be used to compare the differences between two or more arrays and return a new array that is contained in the first array But elements that are not in other arrays. If we put the elements to be removed into an array separately, and then use the array_diff function to compare the original array and the array to be removed, the result will be the other elements except the elements to be removed. The sample code is as follows:
$arr = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'); $remove = array('b'); $arr = array_diff($arr, $remove); print_r($arr); // 输出 Array ( [0] => a [2] => c [3] => d )
When deleting array elements through the array_diff function, you need to pay attention to the following points:
Summary
The above is the method of deleting the elements at the specified position in the PHP array through the unset function, array_splice function and array_diff function. By choosing the appropriate method according to the actual situation, you can easily remove array elements.
The above is the detailed content of How to remove specified elements from an array in php. For more information, please follow other related articles on the PHP Chinese website!