Home  >  Article  >  Backend Development  >  Using the unset() function in PHP to delete an array and rebuild the index_PHP Tutorial

Using the unset() function in PHP to delete an array and rebuild the index_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 17:14:50991browse

We have many ways to delete an array element in PHP, but the most commonly used one is to use the unset function. But how do we rebuild the array index after deleting the middle array element? Please refer to it below.

The code is as follows
 代码如下 复制代码

$arr = array(1,2,3,4);
unset($arr[1]);
echo $array[1]; // error Undefined offset
print_r($arr);

// 输出如下
/**
Array
(
    [0] => 1
    [2] => 3
    [3] => 4
)
**/
$arr = array_values($arr);
print_r($arr);
// 输出如下
/**
Array
(
    [0] => 1
    [1] => 3
    [2] => 4
)
**/

Copy code
$arr = array(1,2,3,4);
unset($arr[1]);
echo $array[1]; // error Undefined offset
print_r($arr);

//The output is as follows
/**
Array
(
    [0] => 1
    [2] => 3
    [3] => 4
)
**/
$arr = array_values($arr);
print_r($arr);
//The output is as follows
/**
Array
(
    [0] => 1
    [1] => 3
    [2] => 4
)
**/

http://www.bkjia.com/PHPjc/628902.htmlwww.bkjia.com
true
http: //www.bkjia.com/PHPjc/628902.html
TechArticleWe have many ways to delete an array element in php, but the most commonly used one is to use the unset function, but delete How do we rebuild the array index if the middle array element is missing? Next...
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