做一个勇于分享的php园丁

PHP开发园地

PHP如何利用unset()删除数组中的元素

在PHP中删除数组元素有以下几种方法:

要删除一个元素,用onset()

unset($array[3]);
unset($array['foo']);

要删除多个不连续的元素,也用unset()

unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);

要删除多个连续的元素,用array_splice()

array_splice($array, $offset, $length);

用这些函数可以从PHP中删除对这些元素的引用。如果你想在数组中保留某个键,并将其值设为空值,可以把空字符串指定给这个元素:

$array[3] = $array['foo'] = '';

除了语法外,用unset()和为元素指定空字符串还有一个逻辑上的区别。前者意味着“这个元素不存在了’,而后者意味着“该元素仍然存在,只是值为空”。

如果处理的是数字,指定0值会更好。所以,如果公司停产了XL1000型号链轮齿,那么应该像这样来更新商品目录:

unset($products['XL1000']);

然而,如果公司只是暂时停止生产XL1000型的链轮齿,并计划在本周的最后几天再接受一个来自工厂的订货,那么这样比较好:

$products['XL1000'] = 0;

如果你unset()一个元素,PHP会调整数组以便循环仍然可以正常完成。但不会因此压缩数组以填补缺少的元素位置。这也正是我们之所以说所有数组都是关联数组的原因所在,即使数组是以数字数组的形式出现也是如此。请看下面的例子:

// create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1]; // prints 'bee'
print $animals[2]; // prints 'cat'
count($animals); // returns 6
// unset()
unset($animals[1]); // removes element $animals[1] = 'bee'
print $animals[1]; // prints '' and throws an E_NOTICE error
print $animals[2]; // still prints 'cat'
count($animals); // returns 5, even though $array[5] is 'fox'
// add new element
$animals[] = 'gnu'; // add new element (not Unix)
print $animals[1]; // prints '', still empty
print $animals[6]; // prints 'gnu', this is where 'gnu' ended up
count($animals); // returns 6
// assign ''
$animals[2] = ''; // zero out value
print $animals[2]; // prints ''
count($animals); // returns 6, count does not decrease
如果想把数组压缩成一个稠密填充的数字数组,可以用array_values( ):

$animals = array_values($animals);

可替代的方案是用array_splice(),它可以自动地重新索引数组以清除空缺的元素位置:

// create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
array_splice($animals, 2, 2);
print_r($animals);
Array
(
[0] => ant
[1] => bee
[2] => elk
[3] => fox
)
如果你把数组当成一个队列看待,并希望从队列中删除一个项目后,仍然能以随机方式访问其中的项目,这种方法非常合适。如果想可靠地删除数组中的第一个或最后一个元素,就要分别用到array_shift()和array_pop()这两个函数。

转载请注明:http://www.itivy.com/php/archive/2012/2/20/php-unset.html

标签: PHP, PHP数组, PHP unset
Posted by php园丁 @ 2012-2-21 12:16:44 阅读(236) 评论(0)
上一篇:PHP中根据时区计算时间
下一篇:PHP中如何动态改变数组大小

我也来参与讨论

你还可以输入600/600个字符 发表评论
称呼: (必填) 登录 | 开通博客
邮箱: (选填) 你的邮箱地址不会被公开
网站: (选填)
验证码: (必填)
看不清换一张 看不清楚换一张