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

WBOY
Release: 2016-05-17 08:57:23
Original
1195 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()函数删除的话,数组的索引值没有变化。

Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!