php删除数组元素示例分享_PHP

WBOY
Release: 2016-06-01 11:55:56
Original
863 people have browsed it

PHP删除数组元素的具体方法:

1.用unset()方法:
复制代码 代码如下:
$a=array("red", "green", "blue", "yellow");  
count($a); //得到4  
unset($a[1]); //删除第二个元素  
count($a); //得到3  
echo $a[2]; //数组中仅有三个元素,本想得到最后一个元素,但却得到blue,  
echo $a[1]; //无值  
?>

缺点:删除数组中的元素后,数组中的元素个数(用count()得到)变了,但数组下标却没有重新排列,还必须用PHP删除数组元素前的key来操作相应的值.

2.用array_splice()方法:
复制代码 代码如下:
$a=array("red", "green", "blue", "yellow");  
count ($a); //得到4  
array_splice($a,1,1); //删除第二个元素  
count ($a); //得到3  
echo $a[2]; //得到yellow  
echo $a[1]; //得到blue
?>

这个程序和前一个相对比,就可以看到,array_splice()不仅删除了元素,还把元素重排了,这样在数组各元素中间就不会有空值!

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!