PHP Method for Deleting Specified Subscript Elements from Array

  • 2021-09-04 23:46:39
  • OfStack

1. The operation of deleting elements when arrays are used as stacks and queues, that is, deleting them regularly in sequence. So, what if you need to delete an element from the middle of the array? We need the unset () function we are going to talk about today.

2. The unset () function allows you to cancel an element in an array, but the array does not rebuild the index, that is, keep the original index, because the index in php has a special meaning.

3. Example display:


<?php 
  $arr = array(1=>'one',2=>'two',3=>'three'); 
    
  // Delete subscript as 2 Elements of  
  unset($arr[2]); // Will get Array(1=>'one',3=>'three') 
 
  // Use array_values() Re-establish the index  
  $aar = array_values($arr); //$aar = array(0=>'one',1=>'three') 
?> 

4. The last sentence in the above example is to re-establish the array index. Here I explain the following: After deleting an element with unset () function, the index subscript order is not re-established. If you need an ordered index subscript, you can recreate the index subscript order using the array_values () function.

Note: Re-indexing here means re-indexing 1 order subscript starting with 0, even if your index is not named after a number, it will be re-indexed.


Related articles: