Home >php教程 >php手册 >php数组删除元素示例

php数组删除元素示例

WBOY
WBOYOriginal
2016-06-13 09:40:241169browse

我们来举一个例子:

复制代码 代码如下:


$arr = array('a','b','c','d'); 
unset($arr[1]); 
print_r($arr); 
?>

我之前想象的是unset之后,数组$arr应该会压缩数组以填补缺少的元素位置,但print_r($arr)之后,结果却不是那样的,最终结果是 Array ( [0] => a [2] => c [3] => d );
如果是这样的话,那我们就来看看数字数组的形式

复制代码 代码如下:


$arr = range(5,10,4); 
print_r($arr);//Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 [4] => 9 [5] => 10 ) 
 unset($arr[1]);//Array ( [0] => 5 [2] => 7 [3] => 8 [4] => 9 [5] => 10 ) 
print_r($arr); 
?>


可以看到输出的形式也是数组是会填补缺少的元素的位置。那么怎么才能做到缺少的元素会被填补并且数组会被重新索引呢?答案是array_splice():
<?php   <BR><p class="codetitle"><span style="CURSOR: pointer" onclick="doCopy('code32117')"><u>复制代码</u></span> 代码如下:</p><p class="code" id="code32117"><br>$arr = array('a','b','c','d');  <br>array_splice($arr,1,1);  <br>print_r($arr); // <span style="font-family: Simsun;font-size:16px; ">Array ( [0] => a [1] => c [2] => d )</span>  <br>?><br></p>

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