Home > Backend Development > PHP Problem > How to delete the first element of an array in PHP?

How to delete the first element of an array in PHP?

Guanhui
Release: 2023-03-02 19:10:01
Original
2774 people have browsed it

How to delete the first element of an array in PHP?

#PHP How to delete the first element of an array?

In PHP, you can delete the first element of the array by using the "array_shift()" function. The function of this function is to move the unit at the beginning of the array out of the array. Its syntax is "array_shift($array)" ”, its parameter $array represents the input array, and the return value is the removed element value.

Sample code

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>
Copy after login

Result

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)
Copy after login
<?php

function array_kshift(&$arr)
{
  list($k) = array_keys($arr);
  $r  = array($k=>$arr[$k]);
  unset($arr[$k]);
  return $r;
}

// test it on a simple associative array
$arr = array(&#39;x&#39;=>&#39;ball&#39;,&#39;y&#39;=>&#39;hat&#39;,&#39;z&#39;=>&#39;apple&#39;);

print_r($arr);
print_r(array_kshift($arr));
print_r($arr);

?>

Output:

Array
(
    [x] => ball
    [y] => hat
    [z] => apple
)
Array
(
    [x] => ball
)
Array
(
    [y] => hat
    [z] => apple
Copy after login

Recommended tutorial: "PHP"

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

Related labels:
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