The following small series for you to share a PHP delete one-dimensional array of a value element of the operation method, has a good reference value, I hope to be helpful. Let's take a look at it with a little knitting.
1. Write for Loop yourself
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 one sentence
foreach ($arr as $k = + $v) {if ($tmp = = $v) unset ($arr [$k]);} $arr = Array_values ($arr);p rint_r ($arr);? >
This time the result
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);p rint_r ($arr);? >
This time the result
Array ([0] = 321 [1] = 322 [2] = 323 [3] = = 325 [4] = 326)
2. Take advantage of PHP's own function, because it is implemented in C, more efficient than its own writing.
Using Array_search and Array_splice, this array_splice automatically resets the sequence values.
$key =array_search ($tmp, $arr); Array_splice ($arr, $key, 1); Var_dump ($arr);
This time the result
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, comparisons can be achieved. Of course the data itself is still one-dimensional.
In the above example, $tmp is a value, and if $tmp is an array or other complex data structure that removes all $tmp elements from $array, the above method works equally well
$arr = Array_merge (Array_diff ($arr, $tmp)); Var_dump ($arr);
The above PHP delete one-dimensional array of one of the value elements of the operation method is the small part to share all the content of everyone, I hope to give you a reference, but also hope that we support PHP Chinese network.
Articles you may be interested in:
PHP to implement anti-color processing of images PHP tips
PHP tips for installing extensions by using the Pecl method
PHP tips for mb_strstr basic PHP Learning Notes