Home > Article > Backend Development > How to remove the previous element of an array in php
Method: 1. Use "array_values($arr)" to convert the array into an index array; 2. Use "array_search(value, array)" to search for values from the index array and return the corresponding index; 2. Use "array_splice($arr, index -1,1)" to delete the previous element from the original array.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
php before removing the array Method of an element
1. Use array_values() to get the array key value and return the key value array
Use array_values() to convert the array Convert to an index array (make sure the array is an index array, so that you can get the position of the specified element in the array below).
<?php header('content-type:text/html;charset=utf-8'); $arr = array("a" => "pear", "b" => "strawberry", "223", "c" => "cherry"); var_dump($arr); $value=array_values($arr); var_dump($value); ?>
2. Use array_search() to search for the specified value from the index array and return the corresponding index.
<?php header('content-type:text/html;charset=utf-8'); $arr = array("a" => "pear", "b" => "strawberry", "223", "c" => "cherry"); var_dump($arr); $value=array_values($arr); var_dump($value); $index=array_search("223",$value); echo $index; ?>
##3. Use array_splice() to delete the previous element
According to the obtained element index, use array_splice() to delete the element at the "$index-1" position in the original array.<?php header('content-type:text/html;charset=utf-8'); $arr = array("a" => "pear", "b" => "strawberry", "223", "c" => "cherry"); var_dump($arr); $value=array_values($arr); var_dump($value); $index=array_search("223",$value); echo "指定元素的索引:".$index; array_splice($arr,$index-1,1); var_dump($arr); ?>Recommended learning: "
PHP Video Tutorial"
The above is the detailed content of How to remove the previous element of an array in php. For more information, please follow other related articles on the PHP Chinese website!