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

How to delete the last element of an array in PHP

PHPz
Release: 2023-04-26 14:13:46
Original
651 people have browsed it

In PHP, you can use the array_pop() function to delete the last element in an array. This function returns the deleted element.

Sample code:

$myArray = [1, 2, 3, 4, 5];

$lastElement = array_pop($myArray);

echo "被删除的元素是:" . $lastElement . "<br>";

print_r($myArray);
Copy after login

The output result is:

被删除的元素是:5
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Copy after login

In the above example, we created an array containing 5 elements$myArray, and then use the array_pop() function to delete the last element 5 and assign it to the variable $lastElement. Finally, the print_r() function is used to output the array $myArray with the last element removed.

In addition to using the array_pop() function, you can also use the unset() function to set the last element in the array to NULL or delete the element:

$myArray = [1, 2, 3, 4, 5];

unset($myArray[count($myArray) - 1]);

print_r($myArray);
Copy after login

The above code uses the unset() function to delete the last element 5 in the array and output the remaining elements.

No matter which deletion method is used, remember to ensure that the key values ​​of the array are still continuous after deleting an array element.

The above is the detailed content of How to delete the last 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