Home >Backend Development >PHP Tutorial >Detailed explanation of steps to delete specified subscript elements in PHP array

Detailed explanation of steps to delete specified subscript elements in PHP array

php中世界最好的语言
php中世界最好的语言Original
2018-05-19 10:45:412175browse

This time I will bring you PHPDelete Detailed steps for specifying subscript elements in an array. What are the precautions for deleting specified subscript elements in an array in PHP? The following is a practical case. , let’s take a look.

1. Previously, we talked about the deletion operation of elements when the array is used as a stack and queue, that is, deletion is performed in order and regularly. So, what should you do 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 elements in an array, but the array will 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'); 
    
  //删除下标为2的元素 
  unset($arr[2]); //将得到Array(1=>'one',3=>'three') 
 
  //使用array_values()重新建立索引 
  $aar = array_values($arr); //$aar = array(0=>'one',1=>'three') 
?>

4. The last sentence of code in the above example is to re-establish the array index. Here I explain the following: because after using the unset() function to delete an element, and The index subscript order is not re-established. If you need sequential index subscripts, you can use the array_values() function to recreate the index subscript order.

Note: The re-indexing mentioned here means: re-creating a sequential subscript starting from 0. Even if your index is not named with a number, it will be re-indexed.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps to replace the article image path with php to the local server

Summary of PHP source code encryption method

The above is the detailed content of Detailed explanation of steps to delete specified subscript elements in PHP array. 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 admin@php.cn