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

PHPz
Release: 2023-04-19 13:43:28
Original
461 people have browsed it

In PHP, deleting an array element is not a difficult thing. You only need to use the array_shift() function to delete the first array element and return the deleted element.

The syntax of the array_shift() function is as follows:

mixed array_shift ( array &$array )
Copy after login

This function receives an array as a parameter and returns the value of the first element deleted in the array. If the array is empty, NULL is returned.

The following is a sample program to delete the first array element:

<?php
    $languages = array("PHP", "JavaScript", "Java", "C#", "Ruby");
    $firstLanguage = array_shift($languages);
    echo "删除的第一个语言是:" . $firstLanguage . "<br>";
    echo "新的数组内容是:<br>";
    print_r($languages);
?>
Copy after login

The running result is:

删除的第一个语言是:PHP
新的数组内容是:
Array
(
    [0] => JavaScript
    [1] => Java
    [2] => C#
    [3] => Ruby
)
Copy after login

As can be seen from the above code:

  • The first element "PHP" in the array is deleted, and the return value is "PHP".
  • The array is re-indexed, and the first element in the new array becomes the second element of the original array.
  • When the print_r() function is called to print the array, the array no longer contains the deleted element "PHP".

It should be reminded that when using the array_shift() function to delete the first element of the array, you need to pay attention to the following points:

  1. The first element of the array is After deletion, the key names of other elements will automatically move forward. If necessary, the array can be re-indexed using the array_values() function.
  2. When the array is empty, calling the array_shift() function will return NULL, and the return value cannot be processed at this time.
  3. Before using the array_shift() function to delete array elements, you need to ensure that the array already exists.

In short, using the array_shift() function can easily delete the first element of an array, making our PHP code simpler and more efficient.

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!

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