In PHP, deleting one or more array elements is not difficult. Specific array elements can be easily removed using the unset() function. In this article, we will discuss how to delete the first two elements of an array in PHP.
PHP unset() function
unset() function is used to delete the specified variable. Use the unset() function in an array to delete a specified element of the array. Once an element is deleted from an array, it is removed from the array and all subsequent elements in the array are moved up one position. Multiple elements in an array can also be deleted using the unset() function.
PHP array function array_shift()
You can use the PHP array function array_shift() to delete the first element of the array and return the value of the element. However, since it only removes the first element, we need to call the function multiple times to remove the first two elements.
PHP array_slice() function
In addition to using the array_shift() function, you can also use the array_slice() function to delete the first two elements in the array. The array_slice() function returns a new array from the array according to the specified conditions, so we can use it to return a new array excluding the first two elements.
The following are the steps to delete the first two elements from a PHP array using the unset() function and the array_slice() function:
Using the unset() function to delete the first two elements
One way is to use the unset() function to remove the first two elements in a loop. As shown below:
$my_array = array('apple', 'banana', 'cherry', 'date'); for($i = 0; $i< 2; $i++){ unset($my_array[$i]); } print_r($my_array);
The output of the above program is as follows:
Array ( [2] => cherry [3] => date )
Use the array_slice() function to delete the first two elements
In this example, array_slice() slices the original array , extract elements starting from index 2, and then save them into a new array:
$my_array = array('apple', 'banana', 'cherry', 'date'); $my_array = array_slice($my_array,2); print_r($my_array);
The output of the above program is as follows:
Array ( [0] => cherry [1] => date )
Use the array_splice() function to delete the first two elements## The #array_splice() function can be used to insert or delete elements. In this example we will use it to remove the first two elements. The format of array_splice() is as follows:
array_splice($array_name, $start, $length);
$array_name: 必需 - 被操作的原始数组名称。 $start: 必需 - 开始的索引位置。 $length: 可选 - 要删除的元素数量。如果未指定,则将删除数组中从$start到数组末尾的所有元素。
$my_array = array('apple', 'banana', 'cherry', 'date'); array_splice($my_array, 0, 2); print_r($my_array);
Array ( [0] => cherry [1] => date )
The above is the detailed content of php array delete first two elements. For more information, please follow other related articles on the PHP Chinese website!