Home > php教程 > php手册 > body text

PHP删除数组中特定元素的两种方法

WBOY
Release: 2016-06-13 11:43:18
Original
1020 people have browsed it

方法一:

复制代码 代码如下:


$arr1 = array(1,3, 5,7,8);
$key = array_search(3, $arr1);

if ($key !== false)
    array_splice($arr1, $key, 1);
var_dump($arr1);
?>


输出:
array(4) { [0]=> int(1) [1]=> int(5) [2]=> int(7) [3]=> int(8) }

方法二:

复制代码 代码如下:


$arr2 = array(1,3, 5,7,8);
foreach ($arr2 as $key=>$value)
{
    if ($value === 3)
        unset($arr2[$key]);
}
var_dump($arr2);
?>


输出:
array(4) { [0]=> int(1) [2]=> int(5) [3]=> int(7) [4]=> int(8) }


总结:可以看到使用array_splice()删除特定值和使用unset删除特定值是有区别的。

array_splice()函数删除的话,数组的索引值也变化了。

unset()函数删除的话,数组的索引值没有变化。

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template