Home  >  Article  >  Backend Development  >  How to delete array elements and reindex in PHP

How to delete array elements and reindex in PHP

青灯夜游
青灯夜游Original
2018-12-26 17:53:147511browse

In PHP, you can first use unset() to delete elements from the array, and then use the array_values() function to automatically numerically index the array; or use the array_splice() function to delete elements in the array, and it will automatically index. The following article will give you a detailed introduction to the method of deleting array elements and re-indexing in PHP. I hope it will be helpful to you.

How to delete array elements and reindex in PHP

First of all, let’s take a look at the PHP functions needed to delete array elements and re-index.

1. unset()

unset() is often used. It is used to destroy specified variables.

Note: unset() is not actually a real function, it is a language structure; it cannot be called by function variables and has no return value. If you try to obtain its return value, an exception will occur.

Syntax:

void unset(mixed $var [, mixed $... ] )

2. array_values() function

array_values() function will return all the values ​​in the array and index the array numerically (starting from 0 and increments by 1).

Syntax:

array array_values(array $array)

3. array_splice() function

array_splice() function can delete the specified element from the array and replace it with a new element; then returns a new array.

Sentence pattern:

array_splice(array,start,length [, array... ])

Below we introduce the method of deleting array elements and re-indexing in PHP through simple code examples.

Example 1:

<?php  
header("content-type:text/html;charset=utf-8"); 
$arr1 = array( 
  
    &#39;php中文网&#39;, // [0] 
    &#39;网址:&#39;, // [1] 
    &#39;m.sbmmt.com&#39; // [2] 
  
); 
  
// 删除索引1处的“网址:”项
unset($arr1[1]);  
  
// 输出修改后的数组
var_dump($arr1); 
  
// 重新索引数组元素
$arr2 = array_values($arr1); 
  
// 输出重新索引的数组
var_dump($arr2); 

?>

Rendering:

How to delete array elements and reindex in PHP

##Example 2:

<?php  
header("content-type:text/html;charset=utf-8"); 
$arr1 = array( 
  
    &#39;php中文网&#39;, // [0] 
    &#39;网址:&#39;, // [1] 
    &#39;m.sbmmt.com&#39; // [2] 
  
); 
// 输出数组
var_dump($arr1); 
echo "<br>";
// 删除索引1处的“网址:”项
array_splice($arr1, 1, 1);    
// 输出修改后的数组
var_dump($arr1); 
  

?>

Rendering:


How to delete array elements and reindex in PHP

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

The above is the detailed content of How to delete array elements and reindex 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 admin@php.cn