Home >Backend Development >PHP Problem >How to delete the last few elements of an array in php

How to delete the last few elements of an array in php

WBOY
WBOYOriginal
2021-12-02 11:09:012089browse

In PHP, you can use the "array_splice()" function to delete the last few elements of the array. This function is used to delete the specified elements in the array. Just set the parameter "start" to a negative number to remove the elements from the array. Delete the specified number of elements from the end, the syntax is "array_splice(array, start, number of elements)".

How to delete the last few elements of an array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

How to delete an array in php The last few elements

You can use the array_splice() function to delete the last few elements of the array. The array_splice() function removes the selected element from the array and replaces it with the new element. . This function will also return the array containing the removed elements.

Tip: If the function does not remove any elements (length=0), the replaced array will be inserted from the position of the start parameter (see Example 2).

Note: The key names in the replaced array are not retained.

The syntax of this function is as follows:

array_splice(array,start,length,array)

What needs to be noted is:

How to delete the last few elements of an array in php

Let’s take an example to see how to delete an array. The last few elements of the array, the example is as follows:

Delete the last two elements of the array

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
array_splice($a1,-2,2);
print_r($a1);
?>

Output result:

How to delete the last few elements of an array in php

Delete the last three elements of the array Bit element

<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
array_splice($a1,-3,3);
print_r($a1);
?>

Output result:

How to delete the last few elements of an array in php

If you are interested, you can click on "PHP Video Tutorial" for more information Learning of PHP knowledge.

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