PHP introduces the function used to delete array elements. We often deal with arrays when writing actual code, which is difficult for beginners. Today, we will introduce how to delete arrays in PHP. we often deal with arrays when writing actual code, which is difficult for beginners. Today, we will introduce how to delete array elements in PHP.
It is very easy to add elements to arrays in PHP. just use the value assignment function. The Keys of the arrays are automatically added. but what about deleting the elements in the arrays? Have you ever thought about it? Is it rare? Recently, when I was dealing with a shopping basket program, I encountered the problem of using PHP to delete array elements. after searching for a long time, I finally found the method for deleting arrays, which is actually very simple.
At first, I referred to the method in the article "string array, delete array elements" (in OSO) and used unset, but it has a defect. for example, $ a is an array:
- <? $ A = array ("red", "green", "blue", "yellow ");
- Count ($ a); // Get 4
- Unset ($ a [1]); // deletes the second element.
- Count ($ a); // Get 3
- Echo $ a [2]; // The array contains only three elements. In this example, we want to get the last element, but we get blue,
- Echo $ a [1]; // no value
- ?>
-
That is to say, after PHP deletes the array elements, the number of elements in the array (obtained by count () has changed, but the array subscript has not been rearranged, you must also use the key before the array to delete the corresponding value.
Later, I used another method. In fact, it was not called a "method" at all. Instead, I used the PHP4 ready-made function array_splice ().
- <? $ A = array ("red", "green", "blue", "yellow ");
- Count ($ a); // Get 4
- Array_splice ($ a,); // deletes the second element.
- Count ($ a); // Get 3
- Echo $ a [2]; // obtain yellow
- Echo $ a [1]; // Get blue
- ?>
-
By comparing this program with the previous one, we can see that array_splice () not only deletes elements, but also rearranges elements, in this way, there will be no null values (such as $ a [1] in values) between the elements of the array.
Array_splice () is actually a function to replace array elements. However, if no replacement value is added, the elements are simply deleted. the usage of array_splice () is as follows:
Array array_splice (array input, int offset [, int length [, array replacement])
The input parameter is an array to be operated. the offset parameter starts from the first element and starts from the first element when the offset parameter is negative; length is the number of elements to be replaced/PHP deleted from the array. if it is omitted, it starts from offset to the end of the array. it can be positive or negative. The principle is the same as offset. relacement is the value to be replaced.
Bytes. Today, we will introduce how to delete arrays in PHP...