Home  >  Article  >  Backend Development  >  Summary of usage of how to delete an element in an array in php

Summary of usage of how to delete an element in an array in php

伊谢尔伦
伊谢尔伦Original
2017-06-24 10:04:251439browse

Remove the value of the $tmp element from the array

 '321','1' => '322','2' => '323','3' => '324','4' => '325','5' => '326',
);

Code

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

At this time

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

reset the index , adding a sentence

$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

$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. Prioritize using the functions that come with PHP, because they are implemented in C and are more efficient than writing them yourself.

  1. 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);

Result at this time

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

$arr = array_merge(array_diff($arr, array($tmp)));
var_dump($arr);

Result

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 is the detailed content of Summary of usage of how to delete an element in an array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]