开发者

Is there a native PHP function for grabbing (and unsetting) an array element?

I just wondered if there were an native PHP function that would replicate the following snippet?

<?php
$array = array(0 => 'element1', 1 => 'element2');
$element1 = $array[0];
unset($array[0]);
?>

Basically, I wish to grab an array element but unset that par开发者_开发知识库ticular key at the same time. Is this possible?


There is array_splice() to extract elements from any position but the way you mention in your question is probably more efficient than that.


For a certain cases:

  • array_pop() / Pop the element off the end of array
  • array_shift() / Shift an element off the beginning of array

General version:

  • array_splice() / Remove a portion of the array and replace it with something else


array_shift removed the first item of an array:

$array = array(0 => 'element1', 1 => 'element2');
$element1 = array_shift($array);

But it also reindexes the array so that the remaining array would be equal to:

$array = array('element2');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜