Home > Article > Backend Development > How to delete array elements and reindex in PHP
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.
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( 'php中文网', // [0] '网址:', // [1] 'm.sbmmt.com' // [2] ); // 删除索引1处的“网址:”项 unset($arr1[1]); // 输出修改后的数组 var_dump($arr1); // 重新索引数组元素 $arr2 = array_values($arr1); // 输出重新索引的数组 var_dump($arr2); ?>
Rendering:
<?php header("content-type:text/html;charset=utf-8"); $arr1 = array( 'php中文网', // [0] '网址:', // [1] 'm.sbmmt.com' // [2] ); // 输出数组 var_dump($arr1); echo "<br>"; // 删除索引1处的“网址:”项 array_splice($arr1, 1, 1); // 输出修改后的数组 var_dump($arr1); ?>Rendering:
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!