array_shift_variation8.phpt 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. --TEST--
  2. Test array_shift() function : usage variations - maintaining referenced elements
  3. --FILE--
  4. <?php
  5. /* Prototype : mixed array_shift(array &$stack)
  6. * Description: Pops an element off the beginning of the array
  7. * Source code: ext/standard/array.c
  8. */
  9. /*
  10. * From a comment left by Traps on 09-Jul-2007 on the array_shift documentation page:
  11. * For those that may be trying to use array_shift() with an array containing references
  12. * (e.g. working with linked node trees), beware that array_shift() may not work as you expect:
  13. * it will return a *copy* of the first element of the array,
  14. * and not the element itself, so your reference will be lost.
  15. * The solution is to reference the first element before removing it with array_shift():
  16. */
  17. echo "*** Testing array_shift() : usage variations ***\n";
  18. // using only array_shift:
  19. echo "\n-- Reference result of array_shift: --\n";
  20. $a = 1;
  21. $array = array(&$a);
  22. $b =& array_shift($array);
  23. $b = 2;
  24. echo "a = $a, b = $b\n";
  25. // solution: referencing the first element first:
  26. echo "\n-- Reference first element before array_shift: --\n";
  27. $a = 1;
  28. $array = array(&$a);
  29. $b =& $array[0];
  30. array_shift($array);
  31. $b = 2;
  32. echo "a = $a, b = $b\n";
  33. echo "Done";
  34. ?>
  35. --EXPECTF--
  36. *** Testing array_shift() : usage variations ***
  37. -- Reference result of array_shift: --
  38. Strict Standards: Only variables should be assigned by reference in %s on line %d
  39. a = 1, b = 2
  40. -- Reference first element before array_shift: --
  41. a = 2, b = 2
  42. Done