tags:

views:

53

answers:

3

Hello,

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 particular key at the same time. Is this possible?

A: 

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');
Gumbo
+1  A: 

For a certain cases:

General version:

  • array_splice() / Remove a portion of the array and replace it with something else
The MYYN
+1  A: 

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

Pekka