";print_r ($myArray);```Output results"/> ";print_r ($myArray);```Output results">

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

How to delete the last element of an array in PHP

PHPz
PHPzOriginal
2023-04-26 10:28:18624browse

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

The output result is:

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

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

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!

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