Home > Article > Backend Development > How to remove elements from array in php
In PHP development, arrays are one of the frequently used data types. In some cases we need to remove elements from an array. PHP provides methods to achieve this functionality.
1. Use the unset() function
The unset() function is used to release the memory of the specified variable. When it is applied to an array element, the element will be deleted.
For example:
$array = array("a", "b", "c"); unset($array[1]); print_r($array);
In the above code, the $array array contains three elements: a, b and c. By using the unset() function and specifying that the index of the element to be deleted is 1, the b element is deleted. The output result is:
Array ( [0] => a [2] => c )
2. Use the array_splice() function
array_splice() function to delete elements from the array and return the deleted elements. With this function, you can remove an element from an array like this:
$array = array("a", "b", "c"); $removed = array_splice($array, 1, 1); print_r($array); print_r($removed);
This code removes the second element in the array. The first parameter is an array, the second parameter is the starting index of the element to be deleted, and the third parameter is the number of elements to be deleted. The output result is:
Array ( [0] => a [1] => c ) Array ( [0] => b )
3. Use array_diff() function
array_diff() function is used to compare two arrays and return elements that exist in one array but not in the other array. We can pass the original array and an array containing these elements to the function and it will return a new array that does not contain these elements.
For example:
$array = array("a", "b", "c"); $removed = array("b"); $new_array = array_diff($array, $removed); print_r($new_array);
This code will remove the second element in the array. If you want to remove multiple elements, you can specify all the elements to be removed in the $removed array. The output result is:
Array ( [0] => a [1] => c )
Summary:
In PHP, you can use the unset() function, array_splice() function and array_diff() function to remove elements from an array. Either way, we can easily remove unwanted elements from the array.
The above is the detailed content of How to remove elements from array in php. For more information, please follow other related articles on the PHP Chinese website!