Home >Backend Development >PHP Tutorial >How to delete a certain value element in a one-dimensional array using php techniques
The following editor will share with you an article on how to delete a certain value element in a one-dimensional array in PHP. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor and take a look.
1. Write your own for loop
Remove the value of the $tmp element from the array
<?php $tmp = '324'; $arr = array( '0' => '321', '1' => '322', '2' => '323', '3' => '324', '4' => '325', '5' => '326', );
Code
foreach( $arr as $k=>$v) { if($tmp == $v) unset($arr[$k]); } print_r($arr); ?>
at this time
Array ( [0] => 321 [1] => 322 [2] => 323 [4] => 325 [5] => 326 )
To reset the index, add
foreach( $arr as $k=>$v) { if($tmp == $v) unset($arr[$k]); } $arr = array_values($arr); print_r($arr); ?>
The result at this time
Array ( [0] => 321 [1] => 322 [2] => 323 [3] => 325 [4] => 326 )
array_merge() can also achieve the same effect
foreach( $arr as $k=>$v) { if($tmp == $v) unset($arr[$k]); } $arr = array_merge($arr); print_r($arr); ?>
The result at this time
Array ( [0] => 321 [1] => 322 [2] => 323 [3] => 325 [4] => 326 )
2 .Prefer using the functions that come with PHP, because they are implemented in C and are more efficient than writing them yourself.
Use array_search and array_splice, where array_splice automatically resets the sequence value.
$key=array_search($tmp ,$arr); array_splice($arr,$key,1); var_dump($arr);
The result at this time
Array ( [0] => 321 [1] => 322 [2] => 323 [3] => 325 [4] => 326 )
Best Practices
$arr = array_merge(array_diff($arr, array($tmp))); var_dump($arr);
Results
Array ( [0] => 321 [1] => 322 [2] => 323 [3] => 325 [4] => 326 )
Here, if the array elements are complex data structures, comparison can also be achieved. Of course the data itself is still one-dimensional.
In the above example, $tmp is a value. If $tmp is an array or other complex data structure, delete all elements contained in $tmp from $array. The above method is also valid.
$arr = array_merge(array_diff($arr, $tmp)); var_dump($arr);
The above PHP method of deleting a certain value element in a one-dimensional array is all the content shared by the editor. I hope it can give you a reference, and I hope Please support php Chinese website.
PHP implements the inverse color processing function of pictures
Example of php installing extension through pecl method to explain php skills
php study notes: basic usage of mb_strstr php skills
The above is the detailed content of How to delete a certain value element in a one-dimensional array using php techniques. For more information, please follow other related articles on the PHP Chinese website!