array_reduce.phpt 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. --TEST--
  2. Test array_reduce() function
  3. --INI--
  4. precision=14
  5. --FILE--
  6. <?php
  7. /* Prototype: array array_reduce(array $array, mixed $callback, mixed $initial);
  8. Description: Iteratively reduce the array to a single value via the callback
  9. */
  10. $array = array('foo', 'foo', 'bar', 'qux', 'qux', 'quux');
  11. echo "\n*** Testing array_reduce() to integer ***\n";
  12. function reduce_int($w, $v) { return $w + strlen($v); }
  13. $initial = 42;
  14. var_dump(array_reduce($array, 'reduce_int', $initial), $initial);
  15. echo "\n*** Testing array_reduce() to float ***\n";
  16. function reduce_float($w, $v) { return $w + strlen($v) / 10; }
  17. $initial = 4.2;
  18. var_dump(array_reduce($array, 'reduce_float', $initial), $initial);
  19. echo "\n*** Testing array_reduce() to string ***\n";
  20. function reduce_string($w, $v) { return $w . $v; }
  21. $initial = 'quux';
  22. var_dump(array_reduce($array, 'reduce_string', $initial), $initial);
  23. echo "\n*** Testing array_reduce() to array ***\n";
  24. function reduce_array($w, $v) { $w[$v]++; return $w; }
  25. $initial = array('foo' => 42, 'bar' => 17, 'qux' => -2, 'quux' => 0);
  26. var_dump(array_reduce($array, 'reduce_array', $initial), $initial);
  27. echo "\n*** Testing array_reduce() to null ***\n";
  28. function reduce_null($w, $v) { return $w . $v; }
  29. $initial = null;
  30. var_dump(array_reduce($array, 'reduce_null', $initial), $initial);
  31. echo "\nDone";
  32. ?>
  33. --EXPECTF--
  34. *** Testing array_reduce() to integer ***
  35. int(61)
  36. int(42)
  37. *** Testing array_reduce() to float ***
  38. float(6.1)
  39. float(4.2)
  40. *** Testing array_reduce() to string ***
  41. string(23) "quuxfoofoobarquxquxquux"
  42. string(4) "quux"
  43. *** Testing array_reduce() to array ***
  44. array(4) {
  45. ["foo"]=>
  46. int(44)
  47. ["bar"]=>
  48. int(18)
  49. ["qux"]=>
  50. int(0)
  51. ["quux"]=>
  52. int(1)
  53. }
  54. array(4) {
  55. ["foo"]=>
  56. int(42)
  57. ["bar"]=>
  58. int(17)
  59. ["qux"]=>
  60. int(-2)
  61. ["quux"]=>
  62. int(0)
  63. }
  64. *** Testing array_reduce() to null ***
  65. string(19) "foofoobarquxquxquux"
  66. NULL
  67. Done