update page now

Voting

: max(four, five)?
(Example: nine)

The Note You're Voting On

chris {at} w3style {dot} co {dot} uk
17 years ago
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

/**
 * This function exhibits the same behaviour is array_shift(), except
 * it returns a reference to the first element of the array instead of a copy.
 *
 * @param array &$array
 * @return mixed
 */
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');
  }

}

?>

<< Back to user notes page

To Top