Home >Backend Development >PHP Problem >How to delete the 5th element in an array in php
2 methods: 1. Use array_splice(), just set the second parameter to 4 and the third parameter to 1, the syntax is "array_splice($arr,4,1)". 2. Use unset(), the syntax "unset($arr[4])" is suitable for index arrays, and delete the element with index 4.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php delete array Method for the 5th element
Method 1: Use array_splice() function
array_splice() function can start from the specified position and delete the specified number of array elements.
You only need to set the starting position to 4 and the number of deletions to 1 to delete the 5th element (starting after the 4th element).
Example:
<?php header("Content-type:text/html;charset=utf-8"); $arr = array('one','two','three',5,6,'php',7,8); var_dump($arr); //删除第5个元素 array_splice($arr,4,1); var_dump($arr); ?>
<?php header("Content-type:text/html;charset=utf-8"); $arr=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"1","e"=>"2","f"=>"3"); var_dump($arr); //删除第5个元素 array_splice($arr,4,1); var_dump($arr); ?>
##2. Use the unset() function
If you want to delete an element in the array, you can use unset(). The unset() function allows you to cancel elements in an array, but the array will not re-index, that is, the original index will be maintained, because the index in PHP has a special meaning. Example: Delete the 5th element (element with index 4)<?php header("Content-type:text/html;charset=utf-8"); $arr = array('one','two',1,2,'three',5,6,'php',7,8); var_dump($arr); //删除第5个元素 unset($arr[4]); var_dump($arr); ?>
Instructions:
The array_splice() method is suitable for indexed arrays and associative arrays. The unset() method is suitable for index arrays; in associative arrays, you need to get the string key name of the fifth element first, and then delete the element based on the key name, but this is too troublesome. Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to delete the 5th element in an array in php. For more information, please follow other related articles on the PHP Chinese website!