Home > Article > Backend Development > How to easily delete the first item of an array in php
PHP is a popular programming language that can handle arrays easily, so it is widely used in web development. Although PHP provides many built-in functions to handle arrays, how to remove the first item from an array is a problem that bothers many people. In this article, we will discuss how to easily delete the first item of an array using PHP.
First, let’s take a look at how to use the array_shift() function to delete the first item of an array. The array_shift() function removes the first element from the array and returns the value of that element. Here is a simple example:
<?php $fruits = array("apple", "banana", "orange"); $first_fruit = array_shift($fruits); echo "The first fruit is $first_fruit"; ?>
The output of the above example is as follows:
The first fruit is apple
As you can see, in the above code, we use the array_shift() function to remove the first One element, namely "apple". Then the array is processed, and the result is as follows:
Array ( [0] => banana [1] => orange )
In the above example, the $first_fruit variable contains the value of the deleted element. But if you just want to remove the element and throw it away, you can use the following code:
<?php $fruits = array("apple", "banana", "orange"); array_shift($fruits); print_r($fruits); ?>
The output will be as follows:
Array ( [0] => banana [1] => orange )
In the above code, we have not declared a variable to store the removed The value of the element, but directly uses the print_r() function to print the array. Now, the $fruits variable only contains the remaining elements, which are "banana" and "orange".
In addition to the array_shift() function, you can also use the array_slice() function to delete the first element of the array. The array_slice() function is used to extract a segment of elements from an array and return its subarray. If we use the array_slice() function to extract all elements starting from index position 1 as shown below:
<?php $fruits = array("apple", "banana", "orange"); $fruits = array_slice($fruits, 1); print_r($fruits); ?>
The output obtained is the same as the above delete function:
Array ( [0] => banana [1] => orange )
In the above code , we use the array_slice() function to extract all elements starting from index position 1 and store them back in the $fruits variable. Therefore, the first element "apple" is removed and only "banana" and "orange" are left in the array.
Summary:
In PHP, you can easily delete the first element of an array using the array_shift() or array_slice() function. If you need to remove other elements, you can use a similar method to array_slice(). Hope this article helps you to work with arrays easily.
The above is the detailed content of How to easily delete the first item of an array in php. For more information, please follow other related articles on the PHP Chinese website!