php Deleting a Value Element in a One Dimensional Array

  • 2021-09-04 23:47:43
  • OfStack

1. Write your own for loop

Remove the value of the element $tmp from 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 a sentence


foreach( $arr as $k=>$v) {
 if($tmp == $v) unset($arr[$k]);
}
$arr = array_values($arr);
print_r($arr);
?>

Result at this time


Array
(
 [0] => 321
 [1] => 322
 [2] => 323
 [3] => 325
 [4] => 326
)

array_merge () can achieve the same effect


foreach( $arr as $k=>$v) {
 if($tmp == $v) unset($arr[$k]);
}
$arr = array_merge($arr);
print_r($arr);
?>

Result at this time


Array
(
 [0] => 321
 [1] => 322
 [2] => 323
 [3] => 325
 [4] => 326
)

2. Preferential use of php comes with the function, because it is implemented with C, write more efficient than their own.

Use array_search and array_splice, where array_splice automatically resets the sequence values.


$key=array_search($tmp ,$arr);
array_splice($arr,$key,1);
var_dump($arr);

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


foreach( $arr as $k=>$v) {
 if($tmp == $v) unset($arr[$k]);
}
print_r($arr);
?>
0

Here, if the array elements are complex data structures, the comparison can also be realized. Of course, the data itself is still 1-dimensional.

In the above example, $tmp is a value. If $tmp is an array or other complex data structure, delete all the elements contained in $tmp from $array. The above method is also effective


foreach( $arr as $k=>$v) {
 if($tmp == $v) unset($arr[$k]);
}
print_r($arr);
?>
1

Related articles: