PHP is a very popular web development language that provides many useful functions and features, including arrays. Arrays are one of the most commonly used data types in PHP and can be used to store and manipulate large amounts of data.
Arrays are usually used as containers to store related data in PHP. When dealing with arrays, we often need to delete or modify elements at a specific index. In this article, we will discuss how to delete a specified subscript from an array in PHP.
First of all, we need to make it clear: the subscript of a PHP array can be a number or a string. If the subscript is a number, the array is called an indexed array; if the subscript is a string, the array is called an associative array. Below we will discuss how to delete specified subscript elements in index arrays and associative arrays respectively.
Delete the specified subscript element in the index array
In PHP, there are two ways to delete the specified subscript element in the index array: use the unset function or use the array_splice function. We'll cover both methods in turn.
Use the unset function to delete the specified subscript element
The unset function is one of the keywords used to destroy variables in PHP. When we use the unset function to delete an element in the array, the element and its corresponding subscript will be completely deleted, and the subscripts of other elements will also be reordered.
For example:
$fruits = array('apple', 'banana', 'cherry', 'date'); unset($fruits[1]); print_r($fruits);
The above code will delete the banana element with index 1, and the output result is:
Array ( [0] => apple [1] => cherry [2] => date )
Use the array_splice function to delete the specified subscript element
## The #array_splice function is one of the functions in PHP used to delete, insert or replace array elements. It deletes a specified number of elements from the original array starting at a specified index position and replaces them with new elements. If you do not provide an element to insert or replace, the function will delete the specified element. For example:$fruits = array('apple', 'banana', 'cherry', 'date'); array_splice($fruits, 1, 1); print_r($fruits);
Array ( [0] => apple [1] => cherry [2] => date )
$fruits = array( 'a' => 'apple', 'b' => 'banana', 'c' => 'cherry', 'd' => 'date' ); $fruits = array_filter($fruits, function ($key) { return $key !== 'b'; }, ARRAY_FILTER_USE_KEY); print_r($fruits);
Array ( [a] => apple [c] => cherry [d] => date )
The above is the detailed content of How to delete elements with specified subscript in php array. For more information, please follow other related articles on the PHP Chinese website!