Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. /**
  2. * Static utility class for working with the PHP array primitive type.
  3. */
  4. abstract class Arrays
  5. {
  6. /**
  7. * Unsets and returns the value at index $key in the given array.
  8. *
  9. * Example:
  10. * <br />
  11. * <pre>
  12. * use Chadicus\Util\Arrays;
  13. * $array = ['a', 'b', 'c'];
  14. * $result = Arrays::getAndUnset($array, 1);
  15. * var_dump($result);
  16. * var_dump($array);
  17. * </pre>
  18. * <br />
  19. * Output:
  20. * <pre>
  21. * string(1) "b"
  22. * array(2) {
  23. * [0] =>
  24. * string(1) "a"
  25. * [2] =>
  26. * string(1) "c"
  27. * }
  28. * </pre>
  29. *
  30. * @param array &$array The array that contains a value at index $key.
  31. * @param integer|string $key The key in $array to unset and value to be returned.
  32. *
  33. * @return mixed
  34. */
  35. final public static function getAndUnset(array &$array, $key)
  36. {
  37. if (!array_key_exists($key, $array)) {
  38. return null;
  39. }
  40.  
  41. $result = $array[$key];
  42. unset($array[$key]);
  43. return $result;
  44. }
  45.  
  46. /**
  47. * Move the element at index $sourceKey to index $destinationKey.
  48. *
  49. * Example:
  50. * <pre>
  51. * use Chadicus\Util\Arrays;
  52. * $array = ['foo' => 'bar'];
  53. * Arrays::rename($array, 'foo', 'goo');
  54. * var_dump($array);
  55. * </pre>
  56. * Output:
  57. * <pre>
  58. * array(1) {
  59. * 'goo' =>
  60. * string(3) "bar"
  61. * }
  62. * </pre>
  63. *
  64. * @param array &$array The array that contains a value at index $sourceKey.
  65. * @param string $sourceKey The index of the source value.
  66. * @param string $destinationKey The new index name.
  67. *
  68. * @return void
  69. */
  70. final public static function rename(array &$array, $sourceKey, $destinationKey)
  71. {
  72. if (array_key_exists($sourceKey, $array)) {
  73. $array[$destinationKey] = $array[$sourceKey];
  74. unset($array[$sourceKey]);
  75. return;
  76. }
  77. }
  78.  
  79. /**
  80. * Attempts to divide the given input array into groups of equal size.
  81. *
  82. * @param array $input The array to batch.
  83. * @param int $batchSize The size of each group.
  84. *
  85. * @return array
  86. */
  87. final public static function batch(array $input, $batchSize)
  88. {
  89. return array_chunk($input, ceil(count($input)/$batchSize), true);
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement