Home > Article > Backend Development > Several ways to delete array elements in php_PHP tutorial
There are many ways to delete array elements in PHP. PHP has two built-in functions, array_slice() and array_flip(), which you can refer to. We first use the php function to implement
array_slice(). The first parameter is the array to be cut, the second parameter is the starting position, and the third parameter is the length.
Just cut the $arr array and count 3 elements from the 0th element downwards.
The code is as follows
|
Copy code
|
||||||||||
array("a","b","c","d","e","f","g") $arr = array_slice($arr, 0, 3);
array_flip achieves deduplication effect phperz~com
array_flip is a function that reverses the keys and values of an array. It has a feature that if two values in the array are the same, the last key and value will be retained after the reversal. Taking advantage of this feature, we use it to indirectly Implementation of array deduplication. |
The code is as follows | Copy code |
$arr = array("a"=>"a1","b"=>'b1',"c"=>"a2","d"=>"a1"); $arr1 = array_flip($arr); print_r($arr1);//Reverse it first, remove duplicate values, and output Array ([a1] => d [b1] => b [a2] => c ) $arr2 = array_flip($arr); print_r($arr2);//Reverse it again to get the deduplicated array and output Array ( [a1] => d [b1] => b [a2] => c ) $arr3 = array_unique($arr); print_r($arr3);//Use PHP’s array_unique function to remove duplicates and output Array ([a] => a1 [b] => b1 [c] => a2 ) ?> The following is the unset method that I commonly used before to achieve deletion
The code is as follows: The code is as followsCopy code
|
$arr = array('a','b','c','d'); <🎜>
unset($arr[1]); <🎜>
print_r($arr); <🎜>
?>
After print_r($arr), the result is not like that. The final result is Array ( [0] => a [2] => c [3] => d
http://www.bkjia.com/PHPjc/631614.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631614.htmlTechArticleThere are many ways to delete array elements in PHP. PHP has two built-in functions array_slice() You can refer to array_flip(). We first use php functions to implement array_s...
|
|