php removes array elements for sample sharing

  • 2021-01-02 21:47:14
  • OfStack

PHP's method for deleting array elements:

1. unset() method:


<?php
$a=array("red", "green", "blue", "yellow");   
count($a); // get 4   
unset($a[1]); // Delete the first 2 An element    
count($a); // get 3   
echo $a[2]; // Only one in the array 3 An element , Ben wants to be the last 1 An element , But get blue,   
echo $a[1]; // There is no value    
?>

Cons: The number of elements in the array (obtained by count()) changes after the element is removed, but the array subscript is not rearranged, and the corresponding value must be manipulated using key before PHP removes the array element.

2. Use array_splice() method:


<?php
$a=array("red", "green", "blue", "yellow");   
count ($a); // get 4   
array_splice($a,1,1); // Delete the first 2 An element    
count ($a); // get 3   
echo $a[2]; // get yellow   
echo $a[1]; // get blue
?>

Compare this program with the previous one, and you can see that array_splice() not only removes the elements, but also rearranges them so that there are no empty values in the middle of each element of the array!


Related articles: