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

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

Guanhui
GuanhuiOriginal
2020-07-21 13:51:482669browse

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);
?>

Result

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)
<?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

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!

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