As pointed out earlier, in PHP4, array_shift() modifies the input array by-reference, but it doesn't return the first element by reference. This may seem like very unexpected behaviour. If you're working with a collection of references (in my case XML Nodes) this should do the trick.
<?php
function &array_shift_reference(&$array)
{
if (count($array) > 0)
{
$key = key($array);
$first =& $array[$key];
}
else
{
$first = null;
}
array_shift($array);
return $first;
}
class ArrayShiftReferenceTest extends UnitTestCase
{
function testFunctionRemovesFirstElementOfNumericallyIndexedArray()
{
$input = array('foo', 'bar');
array_shift_reference($input);
$this->assertEqual(array('bar'), $input, '%s: The array should be shifted one element left');
}
function testFunctionRemovesFirstElementOfAssociativeArray()
{
$input = array('x' => 'foo', 'y' => 'bar');
array_shift_reference($input);
$this->assertEqual(array('y' => 'bar'), $input, '%s: The array should be shifted one element left');
}
function testFunctionReturnsReferenceToFirstElementOfNumericallyIndexedArray()
{
$foo = 'foo';
$input = array(&$foo, 'bar');
$first =& array_shift_reference($input);
$this->assertReference($foo, $first, '%s: The return value should reference the first array element');
}
function testFunctionReturnsReferenceToFirstElementOfAssociativeArray()
{
$foo = 'foo';
$input = array('x' => &$foo, 'y' => 'bar');
$first =& array_shift_reference($input);
$this->assertReference($foo, $first, '%s: The return value should reference the first array element');
}
function testFunctionReturnsNullIfEmptyArrayPassedAsInput()
{
$input = array();
$first = array_shift_reference($input);
$this->assertNull($first, '%s: Array has no first element so NULL should be returned');
}
}
?>