Home >Backend Development >PHP Problem >How to delete data from array header in php

How to delete data from array header in php

PHPz
PHPzOriginal
2023-04-26 14:21:06506browse

In PHP, deleting an element in an array is a very basic operation. Deleting data from the head of the array means we are removing the first data in the array. In this article, we will learn how to delete data from the head of an array using the array_shift() function available in PHP.

array_shift() function is used to pop an element from the beginning of the array and return the element while updating the array. The following is the syntax of the function:

mixed array_shift ( array &$array )

The following is an explanation of the parameters of the function:

  • array: Required. Indicates the array to be operated on;

This function returns the value of the popped array element, or NULL if the array is empty.

The following is a sample code that demonstrates how to use the array_shift() function to delete data from the head of an array:

$fruits = array("apple", "banana", "cherry");

// 弹出数组中的第一个元素
$first_fruit = array_shift($fruits);

// 输出弹出的元素
echo "Popped element: " . $first_fruit . "<br>";

// 输出剩余的数组元素
foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}

In this sample code, we define an array containing three types of fruits. Using the array_shift() function, we pop the first element in the array, which is "apple", and store it in the variable $first_fruit. We then output this popped element and output the remaining array elements through a foreach loop.

When we execute this code, we will get the following output:

Popped element: apple
banana
cherry

As can be seen from the output, the first element of the array has been successfully popped. Removing data from the head of an array can be useful in many situations, such as in queue implementations.

Summary:

This article describes how to use the array_shift() function in PHP to delete data from the array header. In this article, we discuss the function's syntax, parameters, and return values, and demonstrate a sample code that shows how to use the function. In actual development, we often need to add, delete or modify existing array elements, so it will be very useful to understand the array operation functions provided in PHP.

The above is the detailed content of How to delete data from array header in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn