How to delete the first item of an array in php

PHPz
Release: 2023-04-26 13:49:27
Original
667 people have browsed it

In PHP, if you want to delete the first item of an array, you need to use the array_shift() function to achieve this. This function removes the first element from the array and returns the value of that element. The following is a sample code that uses the array_shift() function to delete the first item of the array:

$arr = array('apple', 'banana', 'orange');
$first_item = array_shift($arr);
echo '删除的元素是:' . $first_item . '<br>';
echo '剩余的数组是:';
print_r($arr);
Copy after login

The above code will output the following:

删除的元素是:apple
剩余的数组是:Array ( [0] => banana [1] => orange )
Copy after login

As you can see, use array_shift() The function successfully deletes the first item in the array and returns the value of the element. The remaining array contains only the remaining two items.

In addition to using the array_shift() function, you can also use the unset() keyword to delete the first item in the array. The following is a sample code that uses unset() to delete the first item of the array:

$arr = array('apple', 'banana', 'orange');
unset($arr[0]);
echo '剩余的数组是:';
print_r($arr);
Copy after login

The above code will output the following:

剩余的数组是:Array ( [1] => banana [2] => orange )
Copy after login

As you can see, use ## The #unset() keyword can also successfully delete the first item in the array. However, unlike the array_shift() function, it does not return the value of the deleted element.

You can easily delete the first item of an array, whether using the

array_shift() function or the unset() keyword. However, it should be noted that when deleting items in the array, the key values ​​​​of the array will be rearranged, so it needs to be used with caution.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!